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.
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:
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:
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:
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:
| Method | Overwrites Duplicates | Custom Merge Logic | Uses Java 8+ Features |
putAll() | Yes | No | No |
| Stream API | Configurable | Yes | Yes |
| Iterative | Configurable | Yes | Partially |
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
HashMapinstances are accessed by multiple threads, consider usingConcurrentHashMapor 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
- How can I compare two lists in python and return matches
- How can I compare two sets of 1000 numbers against each other?
- How can I concatenate two arrays in C?
- How can I concatenate two arrays in Java?
- How can I compile a .NET application to native code?
- How can I configure the heap size when starting a Spring Boot application with embedded Tomcat?
- How can I configure encoding in Maven?
- How can I configure Logback to log different levels for a logger to different destinations?

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 courseTrack 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.