How do I merge the entries of two separate map objects?

You can use putAll() method provided by the Map interface to merge entries of two separate Map objects. The putAll() method copies all the mappings from the specified map to the current map. Pre-existing mappings in the current map are replaced by the mappings from the specified map.

Here is a Java code example:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapPutAllExample {
    public static void main(String[] args) {
        Map<String, String> map1 = new HashMap<>();
        Map<String, String> map2 = new HashMap<>();

        map1.put("key1", "value1");
        map1.put("key2", "value2");
        map2.put("key3", "value3");

        System.out.println("Map1: " + map1);
        System.out.println("Map2: " + map2);

        map1.putAll(map2);

        System.out.println("Merged Map: " + map1);
    }
}

Output:

Map1: {key1=value1, key2=value2}
Map2: {key3=value3}
Merged Map: {key1=value1, key2=value2, key3=value3}

If you want to merge two maps but want to provide a specific behavior in case where a key is present in both maps, you might use Map.merge() available since Java 8.

Let’s assume that you want to concatenate the string values of the map where map keys are the same:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapMergeExample {
    public static void main(String[] args) {
        Map<String, String> map1 = new HashMap<>();
        Map<String, String> map2 = new HashMap<>();

        map1.put("key1", "value1");
        map1.put("key2", "value2");
        map2.put("key1", "value3");
        map2.put("key3", "value4");

        map2.forEach(
                (key, value) -> map1.merge(key, value, (v1, v2) -> v1.concat(",").concat(v2))
        );

        // Output: {key1=value1,value3, key2=value2, key3=value4}
        System.out.println(map1);
    }
}

Output:

{key1=value1,value3, key2=value2, key3=value4}

In this example, the Map.merge() method is called for each key-value pair in map2. If map1 already contains a value for the key, it will replace the value with the result of the lambda expression (v1, v2) -> v1.concat(",").concat(v2). This lambda expression tells Java to concatenate the existing and new values with a comma in between. If map1 doesn’t contain the key, it will simply put the key-value pair from map2 into map1.

So, in conclusion, putAll() is straightforward and simply puts all entries from one map to the other, possibly overwriting existing entries. merge(), On the other hand, allows specifying a behaviour for combining values of duplicate keys, providing more control and flexibility when merging maps.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.