Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How merge list when combine two hashMap objects in Java [duplicate]

Tags:

java

hashmap

I have two HashMaps defined like so:

HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();

Also, I have a 3rd HashMap Object:

HashMap<String, List<Incident>> map3;

and the merge list when combine both.

like image 436
martinixs Avatar asked Jul 12 '13 05:07

martinixs


1 Answers

In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it.

However if it was also a HashMap<String, List<Incident>>. You could use the putAll method.

map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);

If you wanted to merge the lists inside the HashMap. You could instead do this.

map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
for(String key : map2.keySet()) {
    List<Incident> list2 = map2.get(key);
    List<Incident> list3 = map3.get(key);
    if(list3 != null) {
        list3.addAll(list2);
    } else {
        map3.put(key,list2);
    }
}
like image 160
Chase Avatar answered Nov 15 '22 00:11

Chase