How to merge two Map<String, Integer> with Java 8 Stream API

By | March 24, 2023

To merge two Map<String, Integer> using Java 8 Stream API, you can follow these steps:
Combine the key sets of both maps.
Create a new Map<String, Integer> by iterating over the combined key set.
For each key, check if it exists in either map, and add the corresponding values.
Return the new merged map.
Here’s an example code snippet that demonstrates this approach:
Map<String, Integer> map1 = new HashMap<>();
map1.put(“a”, 1);
map1.put(“b”, 2);
Map<String, Integer> map2 = new HashMap<>();
map2.put(“b”, 3);
map2.put(“c”, 4);
Map<String, Integer> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
System.out.println(mergedMap); // Output: {a=1, b=5, c=4}
In the above example, we first combine the key sets of map1 and map2 using the Stream.concat() method. Then, we create a new Map<String, Integer> by iterating over the combined key set using the Collectors.toMap() method. Finally, we check if each key exists in either map and add the corresponding values using the Integer::sum function.

Leave a Reply

Your email address will not be published. Required fields are marked *