I prefer summing the Integers into one of the maps. Not creating a new one
In that case you can use merge method added to Map interface in Java 8. Otherwise take a look at other answers like https://stackoverflow.com/a/33640413
Anyway Map#merge(key, value, merginFunction) method is similar to Map#add(key, value). Only difference is fact that it requires third argument which is:
- function used to decide what value to put in map if it already contains specified key. Decision will be made based on old and new value (so its lambda may look like
(v1, v2) -> v1 + v2 for summing values, or we could use Integer::sum method reference).
So you could simply use:
map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));
Now your map1 will copy all key-values from map2 and in case it already has such key, value will be calculated by adding old and new value. Result will be stored in map under that common key.
DEMO:
Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 1);
m1.put("b", 2);
Map<String, Integer> m2 = new HashMap<>();
m2.put("a", 3);
m2.put("c", 10);
System.out.println(m1);
System.out.println(m2);
//iterate over second map and merge its elements into map 1 using
//same key and sum of values
m2.forEach((k, v) -> m1.merge(k, v, Integer::sum));
System.out.println("===========");
System.out.println(m1);
Output:
{a=1, b=2}
{a=3, c=10}
===========
{a=4, b=2, c=10}
keySets, join them in oneSet, look up each value in each map, sum them up and add them to a new map.HashMapper se? You can create an object that has references to bothHashMaps and acts as a hashmap by query both. A bit like a view on a collection.