This post will discuss how to merge two maps of the same type in Java. The solution returns a new map, containing all mappings in both maps. The merge operation will handle common keys present in both maps.

1. Using putAll() method

A simple solution is to use the Map.putAll() method to copy all mappings from the original map to another map.

Download  Run Code

Output:

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

 
Note that if a key k exists in both maps, the value in hm2 will overwrite the value in hm1. i.e., map[k] = hm2[k]. For example,

Download  Run Code

Output:

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

 
We can avoid making an extra call to the putAll() method by passing the first map to the HashMap constructor.

 
If you need to add contents of a map hm1 to map hm2, you can just do:

2. Using Guava

Guava also provides a builder for creating immutable map instances using the putAll() method, whose successive method invocations can be chained:

Download Code

Output:

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

3. Using Java 8

In Java 8 and above, you can get the stream of elements of both maps, and call the Collectors.toMap() to collect all the map elements into a new map by applying the specified mapping functions to it, to help identify the keys and values. This is demonstrated below:

Download  Run Code

Output:

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

 
The above code throws java.lang.IllegalStateException if a duplicate key is present in both maps. To handle this, provide a merge function to resolve collisions between values associated with the same key.

The following code provides a BinaryOperator to merge values for duplicate keys, where the old value takes precedence over the new value in the stream.

Download  Run Code

Output:

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

That’s all about merging two maps of the same types in Java.