How can I combine two HashMap objects containing the same types?

Mavin picture Mavin · Nov 29, 2010 · Viewed 278.7k times · Source

I have two HashMap objects defined like so:

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

I also have a third HashMap object:

HashMap<String, Integer> map3;

How can I merge map1 and map2 together into map3?

Answer

a_horse_with_no_name picture a_horse_with_no_name · Nov 29, 2010
map3 = new HashMap<>();

map3.putAll(map1);
map3.putAll(map2);