Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practices to merge two maps

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?
like image 818
Sam Joos Avatar asked Dec 06 '14 18:12

Sam Joos


2 Answers

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:

Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();

oldMap.put("1", 10);
oldMap.put("2", 5);
newMap.put("1", 7);

oldMap.forEach((k, v) -> newMap.merge(k, v, (a, b) -> a + b));

System.out.println(newMap); //{1=17, 2=5}

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.

like image 171
Alexis C. Avatar answered Oct 07 '22 13:10

Alexis C.


for( Map.Entry<String,Integer> entry: newMap.entrySet() ) {
    // get key and value from newMap and insert/add to oldMap
    Integer oldVal = oldMap.get( entry.getKey() );
    if( oldVal == null ){
        oldVal = entry.getValue();
    } else {
        oldVal += entry.getValue();
    }
    newMap.put( entry.getKey(), oldVal );
}

Hope that this is what you meant

like image 4
laune Avatar answered Oct 07 '22 15:10

laune