How merge list when combine two hashMap objects in Java

11,230

Solution 1

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);
    }
}

Solution 2

create third map and use putAll() method to add data from ma

HashMap<String, Integer> map1 = new HashMap<String, Integer>();

HashMap<String, Integer> map2 = new HashMap<String, Integer>();

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

You have different type in question for map3 if that is not by mistake then you need to iterate through both map using EntrySet

Share:
11,230
martinixs
Author by

martinixs

Updated on June 08, 2022

Comments

  • martinixs
    martinixs about 2 years

    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.