Sunday, June 4, 2023

How to Merge two HashMap in Java 8 - Map.merge() example Tutorial

In Java 8, you can use the merge() method provided by the Map interface to merge two HashMaps. The merge() method allows you to specify a merging function that determines how conflicting values for the same key should be resolved. 

Here's an example:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating two HashMaps
        Map map1 = new HashMap<>();
        Map map2 = new HashMap<>();

        // Adding key-value pairs to map1
        map1.put("Key1", 1);
        map1.put("Key2", 2);

        // Adding key-value pairs to map2
        map2.put("Key2", 3);
        map2.put("Key3", 4);

        System.out.println("HashMap 1: " + map1);
        System.out.println("HashMap 2: " + map2);

        // Merging the two HashMaps using merge() and resolving conflicts with sum
        map2.forEach((key, value) -> map1.merge(key, value, Integer::sum));

        System.out.println("Merged HashMap: " + map1);
    }
}

In this example, we create two HashMaps: map1 and map2. We add key-value pairs to each map using the put() method. Then, we print the contents of both HashMaps. 

To merge the two HashMaps, we use the merge() method on map1 and pass map2 as an argument. We provide a lambda expression (key, value) -> map1.merge(key, value, Integer::sum) as the merging function. This lambda expression specifies that when a conflict occurs, the values should be summed.

The merge() method takes three arguments: the key, the value from the map2, and the merging function. It merges the key-value pairs from map2 into map1, applying the merging function to resolve conflicts. If the key already exists in map1, the merging function is called with the existing value and the new value, and the result is stored as the new value for the key. If the key is not present in map1, the key-value pair from map2 is added to map1 as is. 

Finally, we print the merged HashMap, map1. 

The output of this example will be:


HashMap 1: {Key1=1, Key2=2}
HashMap 2: {Key2=3, Key3=4}
Merged HashMap: {Key1=1, Key2=5, Key3=4}

As you can see, the values for the common key "Key2" are merged according to the specified merging function, which in this case is the sum of the values. The value for "Key2" becomes 5 in the merged HashMap.

No comments:

Post a Comment