🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Stream API and the Map interface's merge method. This guide will cover different ways to merge two maps, including using the putAll method, the Stream API, and the merge method.Table of Contents
- Introduction
- Using
putAllMethod - Using
StreamAPI - Using
Map.mergeMethod - Conclusion
Introduction
In Java, a Map is a collection that maps keys to values, with each key mapping to at most one value. Merging two maps involves combining their entries and handling cases where both maps contain the same key.
Using putAll Method
The putAll method can be used to merge two maps. However, it will overwrite the values in the first map with the values from the second map when keys are the same.
Example
import java.util.HashMap; import java.util.Map; public class MergeMapsExample { public static void main(String[] args) { Map<String, Integer> map1 = new HashMap<>(); map1.put("apple", 1); map1.put("banana", 2); Map<String, Integer> map2 = new HashMap<>(); map2.put("banana", 3); map2.put("cherry", 4); map1.putAll(map2); System.out.println("Merged Map: " + map1); } } Explanation
putAllmethod copies all entries frommap2tomap1.- If
map1contains a key that is also inmap2, the value frommap2overwrites the value inmap1.
Output:
Merged Map: {apple=1, banana=3, cherry=4} Using Stream API
The Stream API provides a flexible and concise way to merge two maps, allowing you to handle key collisions in a custom way.
Example
import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class MergeMapsExample { public static void main(String[] args) { Map<String, Integer> map1 = new HashMap<>(); map1.put("apple", 1); map1.put("banana", 2); Map<String, Integer> map2 = new HashMap<>(); map2.put("banana", 3); map2.put("cherry", 4); Map<String, Integer> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (value1, value2) -> value1 + value2 )); System.out.println("Merged Map: " + mergedMap); } } Explanation
Stream.concatcombines the entry streams ofmap1andmap2.Collectors.toMapcollects the combined stream into a new map.- The merge function
(value1, value2) -> value1 + value2handles key collisions by summing the values.
Output:
Merged Map: {apple=1, banana=5, cherry=4} Using Map.merge Method
The merge method provides a way to merge two maps directly, allowing you to handle key collisions in a custom way.
Example
import java.util.HashMap; import java.util.Map; public class MergeMapsExample { public static void main(String[] args) { Map<String, Integer> map1 = new HashMap<>(); map1.put("apple", 1); map1.put("banana", 2); Map<String, Integer> map2 = new HashMap<>(); map2.put("banana", 3); map2.put("cherry", 4); map2.forEach((key, value) -> map1.merge(key, value, Integer::sum)); System.out.println("Merged Map: " + map1); } } Explanation
- The
forEachmethod iterates over each entry inmap2. - The
mergemethod updatesmap1with entries frommap2. - The merge function
Integer::sumhandles key collisions by summing the values.
Output:
Merged Map: {apple=1, banana=5, cherry=4} Conclusion
Merging two maps in Java 8 can be accomplished using various methods, each with its own advantages. The putAll method provides a straightforward way to combine maps but overwrites values in case of key collisions. The Stream API offers a flexible and concise approach, allowing custom handling of key collisions. The merge method provides a direct way to combine maps with custom collision handling. Depending on your specific use case and preferences, you can choose the method that best fits your needs.
Comments
Post a Comment
Leave Comment