Java – How to combine two HashMap objects containing the same types

hashmapjava

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?

Best Answer

map3 = new HashMap<>();

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