This post will discuss how to add the contents of a Map to another Map in Java.

1. Using putIfAbsent() method

In Java 8, you can use Map.forEach() to iterate over each entry of the map and invoke the putIfAbsent() method for each mapping. The putIfAbsent() method associates the specified key with the specified value if the key is not already present in the map.

This method is particularly useful to copy all mappings of a map to another, and not replace the existing key-value mappings.

Download  Run Code

Output:

{1=A, 2=B, 3=C, 4=D}

 
You can further shorten the code by passing the method reference of the putIfAbsent() method to forEach().

Download  Run Code

Output:

{1=A, 2=B, 3=C, 4=D}

2. Using merge() method

Another alternative would be to use the merge() method to associate the specified key with a non-null value. It takes the remapping function to recompute the value if already present.

The following code example iterates over the map’s entries and merges its mappings into another map using the merge() method. The remapping function states that the old value takes precedence over the new value in case the key is already present.

Download  Run Code

Output:

{1=A, 2=B, 3=D}

 
The above code can be easily shortened using the Stream API:

Download  Run Code

Output:

{1=A, 2=B, 3=D}

3. Using put() method

You can also iterate over each entry in the map and invoke the put() method for each mapping if and only if the key is not already present in the other map.

Download  Run Code

Output:

{1=A, 2=B, 3=D}

That’s all about adding the contents of a Map to another Map in Java.