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.

2
  • Look at here stackoverflow.com/questions/4299728/… Commented Jul 12, 2013 at 5: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<Incident> is needed. map.putAll() will replace the list, not combine the two. Commented May 9, 2015 at 3:56

4 Answers 4

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe OP want to merge "a"->[1,2] and "a"->[3,4] into "a"->[1,2,3,4], since the value of the map is a List.
Good, point, i'll add something on that.
yes, i want to merge list
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

Comments

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.

1 Comment

CollectionUtils.union doesn't work with maps, only collections.
-1

HashMap has a putAll method.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.