Match key ib Hashmap using arraylist

时间:2015-11-12 11:50:24

标签: java arraylist hashmap

Hi I have an array list which contain some date

ArrayList dates = new ArrayList();

I have list of date something like :

All dates between:2015-10-29
All dates between:2015-10-30
All dates between:2015-10-31
All dates between:2015-11-01
All dates between:2015-11-02
All dates between:2015-11-03

And I have a Hashmap somethin like

HashMap<String,String> segCount=userSegmentDAO.getDateWiseCount(user.getOrgId(), startDate, end_Date,fromDate,endDate);

where I am getting value some thing like

2015-10-29   6
2015-10-31   3
2015-11-02   5

No what I want here I am traversing array list till last and want to compare with hashmap if hash map conatian that date as a key then leave it as it is otherwise put that date as a key in hashmap and placed 0 for value.

3 个答案:

答案 0 :(得分:1)

for (String each: dates ){
            if(!segCount.containsKey(each)){
                segCount.put(each, "0");
            }
        }

However, it is better to use Date instead of String as Map key and array element.

答案 1 :(得分:0)

Or if you use java8

dates.stream()
            .filter(dateString -> !segCount.containsKey(dateString))
            .forEach(dateString -> segCount.put(dateString, "0"));

答案 2 :(得分:0)

In Java 8 you can do

for (String s : dates)
    segCount.putIfAbsent(s, "0");