6

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.

martinixs
  • 325
  • 1
  • 5
  • 16
  • Look at here http://stackoverflow.com/questions/4299728/how-can-i-combine-two-hashmap-objects-of-same-type-in-java – Jayram Jul 12 '13 at 05:26
  • This is quite a different question than the "How can I combine two HashMap objects containing the same types?" This question is about combining **Multi-value** maps. The problem is that a solution for combining the values in the `List` is needed. map.putAll() will replace the list, not combine the two. – Zombies May 09 '15 at 03:56

4 Answers4

7

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);
    }
}
Chase
  • 1,419
  • 12
  • 17
4

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

Use commons collections:

Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);

If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map.

Paul
  • 19,704
  • 14
  • 78
  • 96
hd1
  • 33,938
  • 5
  • 80
  • 91
-1

HashMap has a putAll method.

Refer this : http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

Manish Doshi
  • 1,205
  • 1
  • 9
  • 17