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.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024