How to join or merge two hashmaps in Java

Learn to merge two hashmaps in Java. We will learn to join hashmaps in two cases – ignore duplicate keys (overwrite values) or handle duplicate keys using Java 8.

1. Merge two hashmaps – ignore duplicate keys

This one is simple solution. Simply use HashMap.putAll(HashMap) method which copies all of the mappings from the second map to first map.

As we know hashmap does not allow duplicate keys. So when we merge the maps in this way, for duplicate keys in map1 the value is overwitten by value for same key in map2.

Let’s take an example.

//map 1
HashMap<Integer, String> map1 = new HashMap<>();

map1.put(1, "A");
map1.put(2, "B");
map1.put(3, "C");
map1.put(5, "E");

//map 2
HashMap<Integer, String> map2 = new HashMap<>();

map2.put(1, "G");	//It will replace the value 'A'
map2.put(2, "B");
map2.put(3, "C");
map2.put(4, "D");	//A new pair to be added

//Merge maps
map1.putAll(map2);

System.out.println(map1);

Program output.

{1=G, 2=B, 3=C, 4=D, 5=E}

2. Java 8 combine two hashmaps – handle duplicate keys

If we want to handle the cases where duplicate keys are present in the maps and we do not want to loose the data for any map and for any key. In this case, we can take help of HashMap.merge() function added in Java 8.

merge() function 3 arguments. Key, value and uses a user-provided BiFunction to merge values for duplicate keys.

In our example, we want to append both the strings when a duplicate key is found ONLY WHEN the value is different from previous values associated with key in map1.

//map 1
HashMap<Integer, String> map1 = new HashMap<>();

map1.put(1, "A");
map1.put(2, "B");
map1.put(3, "C");
map1.put(5, "E");

//map 2
HashMap<Integer, String> map2 = new HashMap<>();

map2.put(1, "G");	//It will replace the value 'A'
map2.put(2, "B");
map2.put(3, "C");
map2.put(4, "D");	//A new pair to be added

//Merge maps
map2.forEach(
    (key, value) -> map1.merge( key, value, (v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + "," + v2)
);

System.out.println(map1);

Program output.

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

Notice the value of key "1". It had value A in map1 and G in map2. In merged map, it has combined value as "A,G". We can write any sort of merge logic in provided BiFunction.

Drop me your questions related to merging to hashmaps in Java 8.

Happy Learning !!

Read More :

A Guide to Java HashMap
HashMap merge java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “How to join or merge two hashmaps in Java”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.