HashMap
Java
Data Structures
Programming
Code Optimization

How can I combine two HashMap objects containing the same types?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, a HashMap is a part of the Java Collection Framework and stores data in key-value pairs. Each key is unique and mapped to exactly one value. In cases where you have two HashMap objects containing the same types and you need to combine them into a single HashMap, there are several methods to achieve this, depending on the requirements and specific conditions like handling duplicate keys. Below, we will explore various strategies to merge two HashMaps efficiently.

Method 1: Using putAll()

The simplest way to combine two HashMap objects is by using the putAll() method. This method copies all of the mappings from the specified map to another map. Here's how you can use it:

java
1HashMap<Integer, String> map1 = new HashMap<>();
2map1.put(1, "One");
3map1.put(2, "Two");
4
5HashMap<Integer, String> map2 = new HashMap<>();
6map2.put(3, "Three");
7map2.put(4, "Four");
8
9map1.putAll(map2);

After executing this code, map1 will contain all the elements from map2. However, if there are duplicate keys in both HashMaps, the values from map2 will overwrite those in map1. This method is efficient but might not be suitable if you need to preserve or handle duplicates in a specific way.

Method 2: Stream API in Java 8+

From Java 8 onwards, you can use the Stream API combined with the Collectors.toMap() to merge two maps. This method provides more flexibility as you can specify a merge function that dictates how to handle collisions (i.e., duplicate keys). Here's an example:

java
1HashMap<Integer, String> map1 = new HashMap<>();
2map1.put(1, "One");
3map1.put(2, "Two");
4
5HashMap<Integer, String> map2 = new HashMap<>();
6map2.put(2, "Different Two");
7map2.put(3, "Three");
8
9HashMap<Integer, String> resultMap = Stream.of(map1, map2)
10    .flatMap(map -> map.entrySet().stream())
11    .collect(Collectors.toMap(
12        Map.Entry::getKey,
13        Map.Entry::getValue,
14        (value1, value2) -> value1 + "; " + value2
15    ));

In the above code, if there are duplicate keys, the merging function (value1, value2) -> value1 + "; " + value2 will concatenate the values from both maps, rather than overwriting them.

Method 3: Iterative Approach

If you need to iterate through the keys and decide programmatically how to deal with duplicates, you might take the manual approach:

java
1HashMap<Integer, String> map1 = new HashMap<>();
2map1.put(1, "One");
3map1.put(2, "Two");
4
5HashMap<Integer, String> map2 = new HashMap<>();
6map2.put(2, "Different Two");
7map2.put(3, "Three");
8
9for (Map.Entry<Integer, String> entry : map2.entrySet()) {
10    map1.merge(entry.getKey(), entry.getValue(), (v1, v2) -> v1 + "; " + v2);
11}

This approach provides full control over how values are merged, using the merge method which takes a BiFunction to resolve collisions.

Comparison Table

The following table summarizes the key points of the methods discussed:

MethodOverwrites DuplicatesCustom Merge LogicUses Java 8+ Features
putAll()YesNoNo
Stream APIConfigurableYesYes
IterativeConfigurableYesPartially

Additional Considerations

  • Performance: The choice of method might depend on the performance considerations in your application. For large maps, avoid methods that significantly increase computational complexity.
  • Null Values: Consider how each method handles null values both as keys and values.
  • Concurrent Modifications: If the HashMap instances are accessed by multiple threads, consider using ConcurrentHashMap or synchronizing the map.

In conclusion, merging two HashMap objects in Java can be done in several ways, each with its own advantages and suitability depending on the specific needs of your application. By understanding the characteristics of each method, developers can make informed decisions that best fit their requirements.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms