How can I add a new map to existing map. The maps have the same type Map<String, Integer>
. If the key from new map exists in the old map the values should be added.
Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();
//Data added
//Now what is the best way to iterate these maps to add the values from both?
Hope that this is what you meant
By add, I assume you want to add the integer values, not create a
Map<String, List<Integer>>
.Before java 7, you'll have to iterate as @laune showed (+1 to him). Otherwise with java 8, there is a merge method on Map. So you could do it like this:
What it does is that for each key-value pair, it merges the key (if it's not yet in
newMap
, it simply creates a new key-value pair, otherwise it updates the previous value hold by the existing key by adding the two Integers)Also maybe you should consider using a
Map<String, Long>
to avoid overflow when adding two integers.