Introduction
Merging two maps is a common task in Java, especially when you need to combine data from different sources or when you want to update an existing map with values from another map. Java 8 introduced new methods in the Map interface, such as merge() and putAll(), as well as the Stream API, which provide powerful and flexible ways to merge maps. In this guide, we’ll explore different approaches to merging two maps in Java 8, including how to handle key collisions and combine values when keys overlap.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Merging Two Maps Using
putAll() - Merging Two Maps Using
merge() - Merging Two Maps Using Streams
- Merging Two Maps Using
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Accepts two maps.
- Merges the maps into a single map.
- Handles scenarios where both maps contain the same keys by combining their values.
Example 1:
- Input:
- Map 1:
{1: "Apple", 2: "Banana"} - Map 2:
{2: "Orange", 3: "Grape"}
- Map 1:
- Output:
{1: "Apple", 2: "Banana, Orange", 3: "Grape"}
Example 2:
- Input:
- Map 1:
{1: 10, 2: 20} - Map 2:
{2: 30, 3: 40}
- Map 1:
- Output:
{1: 10, 2: 50, 3: 40}
Solution Steps
- Create Two Maps: Start with two maps that you want to merge.
- Merge the Maps: Use one of the methods available in Java 8 to merge the maps.
- Handle Key Collisions: Define how to combine values when both maps contain the same key.
- Display the Result: Print the merged map.
Java Program
Merging Two Maps Using putAll()
The putAll() method is the simplest way to merge two maps. It adds all key-value pairs from one map into another, overwriting values in the target map if the same key exists.
import java.util.HashMap;
import java.util.Map;
/**
* Java 8 - Merge Two Maps Using putAll()
* Author: https://www.rameshfadatare.com/
*/
public class MergeMapsUsingPutAll {
public static void main(String[] args) {
// Step 1: Create two maps
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "Apple");
map1.put(2, "Banana");
Map<Integer, String> map2 = new HashMap<>();
map2.put(2, "Orange");
map2.put(3, "Grape");
// Step 2: Merge map2 into map1 using putAll()
map1.putAll(map2);
// Step 3: Display the result
System.out.println("Merged Map: " + map1);
}
}
Output
Merged Map: {1=Apple, 2=Orange, 3=Grape}
Explanation
- The
putAll()method copies all key-value pairs frommap2intomap1. - If a key exists in both maps (like key
2), the value frommap2("Orange") overwrites the value frommap1("Banana").
Merging Two Maps Using merge()
The merge() method allows more control over how values are combined when keys overlap. This method requires a BiFunction to specify how to merge the values associated with a key present in both maps.
import java.util.HashMap;
import java.util.Map;
/**
* Java 8 - Merge Two Maps Using merge()
* Author: https://www.rameshfadatare.com/
*/
public class MergeMapsUsingMerge {
public static void main(String[] args) {
// Step 1: Create two maps
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "Apple");
map1.put(2, "Banana");
Map<Integer, String> map2 = new HashMap<>();
map2.put(2, "Orange");
map2.put(3, "Grape");
// Step 2: Merge map2 into map1 using merge()
map2.forEach((key, value) ->
map1.merge(key, value, (v1, v2) -> v1 + ", " + v2)
);
// Step 3: Display the result
System.out.println("Merged Map: " + map1);
}
}
Output
Merged Map: {1=Apple, 2=Banana, Orange, 3=Grape}
Explanation
- The
merge()method checks if the key exists inmap1. If it does, theBiFunctioncombines the old and new values ("Banana"and"Orange") into a single string"Banana, Orange". - If the key doesn’t exist in
map1, the new key-value pair is added.
Merging Two Maps Using Streams
Using the Stream API, you can merge two maps into a new map, offering a flexible and functional approach. This method is particularly useful if you need to perform additional operations during the merge.
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java 8 - Merge Two Maps Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class MergeMapsUsingStreams {
public static void main(String[] args) {
// Step 1: Create two maps
Map<Integer, Integer> map1 = new HashMap<>();
map1.put(1, 10);
map1.put(2, 20);
Map<Integer, Integer> map2 = new HashMap<>();
map2.put(2, 30);
map2.put(3, 40);
// Step 2: Merge maps using Streams
Map<Integer, Integer> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
Integer::sum
));
// Step 3: Display the result
System.out.println("Merged Map: " + mergedMap);
}
}
Output
Merged Map: {1=10, 2=50, 3=40}
Explanation
- The
Stream.concat()method combines the entries ofmap1andmap2into a single stream. - The
Collectors.toMap()method collects these entries into a new map. - The
Integer::sumfunction specifies that if a key exists in both maps, the values should be summed.
Advanced Considerations
-
Null Handling: If there is a possibility of null values in the maps, ensure that the
merge()method or the stream operation handles these cases appropriately, as nulls can causeNullPointerException. -
Performance Considerations: For large maps, consider the performance impact of different merging strategies. The
putAll()method is generally faster but less flexible, whilemerge()and streams offer more control at the cost of additional overhead. -
Order Preservation: If order is important (e.g., you need to maintain insertion order), use
LinkedHashMapinstead ofHashMap.
Conclusion
This guide provides methods for merging two maps in Java 8, covering approaches with putAll(), merge(), and the Stream API. Merging maps is a common task when combining data from different sources, and Java 8 provides powerful tools to do this efficiently while handling key collisions and other complexities. Depending on your specific use case, you can choose the method that best fits your needs for merging maps in Java.