1. Introduction
In Java, merging two maps is a common operation, especially when dealing with collections. The Map.merge() method is used for this purpose, and it allows for the combination of two maps with the option of resolving conflicts using a specified function.
2. Program Steps
1. Import the required packages.
2. Create two Map objects with some overlapping keys.
3. Loop through the entries of the second map, using the merge() method to combine them into the first map.
4. Specify a BiFunction to handle the value merging in case of key collisions.
3. Code Program
// Step 1: Import the required packages
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
public class MapMergeExample {
public static void main(String[] args) {
// Step 2: Create two Map objects with some overlapping keys
Map<String, Integer> map1 = new HashMap<>();
map1.put("Apple", 3);
map1.put("Banana", 2);
map1.put("Cherry", 5);
Map<String, Integer> map2 = new HashMap<>();
map2.put("Banana", 4);
map2.put("Cherry", 4);
map2.put("Date", 2);
// Printing the original maps
System.out.println("Map1: " + map1);
System.out.println("Map2: " + map2);
// Step 3: Loop through the entries of map2 and merge them into map1
// Step 4: Specify a BiFunction to handle the value merging in case of key collisions
BiFunction<Integer, Integer, Integer> mergeFunction = (value1, value2) -> value1 + value2;
map2.forEach((key, value) -> map1.merge(key, value, mergeFunction));
// Printing the merged map
System.out.println("Merged Map: " + map1);
}
}
Output:
Map1: {Banana=2, Cherry=5, Apple=3} Map2: {Banana=4, Cherry=4, Date=2} Merged Map: {Banana=6, Cherry=9, Apple=3, Date=2}
4. Step By Step Explanation
Step 1: Import the necessary packages including HashMap, Map, and BiFunction.
Step 2: Instantiate two Map objects, map1 and map2, and populate them with some initial data, where some keys are overlapping.
Step 3: Loop through each entry of map2, and use the merge() method to combine them into map1.
Step 4: During merging, specify a BiFunction which determines how to resolve the collisions of keys. In this case, it adds up the values of the common keys.
After merging, map1 will be updated with the combined entries of both maps, where the values of overlapping keys are summed up, as demonstrated in the output.