I have two HashMap
How can I sum them easily?
Meaning that for String \"a\" the key will be sum of (value from Map1 + valu
in case you like Java 8:
Map sum(Map... maps) {
return Stream.of(maps) // Stream
can sum up arbitrary amounts of maps. It turns the array of maps into a Stream in the first few lines, then collects all the entries into a new Map while supplying a "merge function" in case of duplicate values.
alternatively something along the lines of
void addToA(HashMap a, HashMap b) {
for (Entry entry : b.entrySet()) {
Integer old = a.get(entry.getKey());
Integer val = entry.getValue();
a.put(entry.getKey(), old != null ? old + val : val);
}
}