Java HashMap - merge() Method
The java.util.HashMap.merge() method is used to merge multiple mapped values for a key. If a specified key is not already associated with a value or null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.
If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
Syntax
public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
key |
Specify the key with which the resulting value is to be associated. |
value |
Specify the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key. |
remappingFunction |
Specify the function to recompute a value if present. |
Return Value
Returns the new value associated with the specified key, or null if no value is associated with the key.
Exception
NA.
Example:
In the example below, the java.util.HashMap.merge() method is used to merge multiple mapped values for a key.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a HashMap HashMap<Integer, String> Map1 = new HashMap<Integer, String>(); HashMap<Integer, String> Map2 = new HashMap<Integer, String>(); //populating Map1 Map1.put(101, "John"); Map1.put(102, "Marry"); Map1.put(103, "Kim"); //populating Map2 Map2.put(101, "M"); Map2.put(102, "F"); Map2.put(103, "M"); //printing the HashMap System.out.println("Map1 contains: " + Map1); System.out.println("Map2 contains: " + Map2); //merging two HashMaps into Map1 Map2.forEach((k,v) -> Map1.merge(k, v, (v1, v2) -> (v1 == v2) ? v1 : v1 + ", " + v2 ) ); //printing the HashMap System.out.println("Map1 contains: " + Map1); } }
The output of the above code will be:
Map1 contains: {101=John, 102=Marry, 103=Kim} Map2 contains: {101=M, 102=F, 103=M} Map1 contains: {101=John, M, 102=Marry, F, 103=Kim, M}
❮ Java.util - HashMap