0
0
JavaHow-ToBeginner · 4 min read

How to Merge Two HashMaps in Java Easily

To merge two HashMap objects in Java, you can use the putAll() method to copy all entries from one map into another. For more control, especially when keys overlap, use the merge() method to combine values based on a custom rule.
📐

Syntax

The basic syntax to merge two HashMaps is:

  • map1.putAll(map2); - Adds all entries from map2 into map1. If keys overlap, map2 values overwrite map1.
  • map1.merge(key, value, BiFunction) - Merges a single key-value pair with a custom function to handle duplicates.
java
map1.putAll(map2);

// Or for custom merging of values
map1.merge(key, value, (v1, v2) -> v1 + v2);
💻

Example

This example shows how to merge two HashMaps using putAll() and how to merge values with merge() when keys overlap.

java
import java.util.HashMap;
import java.util.Map;

public class MergeHashMaps {
    public static void main(String[] args) {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("apple", 10);
        map1.put("banana", 5);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("banana", 7);
        map2.put("orange", 8);

        // Simple merge: map2 entries overwrite map1 if keys clash
        Map<String, Integer> mergedMap = new HashMap<>(map1);
        mergedMap.putAll(map2);
        System.out.println("Merged with putAll(): " + mergedMap);

        // Merge with custom logic to sum values for duplicate keys
        Map<String, Integer> mergedWithSum = new HashMap<>(map1);
        for (Map.Entry<String, Integer> entry : map2.entrySet()) {
            mergedWithSum.merge(entry.getKey(), entry.getValue(), Integer::sum);
        }
        System.out.println("Merged with merge() summing values: " + mergedWithSum);
    }
}
Output
Merged with putAll(): {orange=8, banana=7, apple=10} Merged with merge() summing values: {orange=8, banana=12, apple=10}
⚠️

Common Pitfalls

One common mistake is using putAll() when you want to combine values for duplicate keys, which simply overwrites old values. Another is not initializing the target map before merging, causing NullPointerException. Also, forgetting to handle null values in merge() can cause errors.

java
import java.util.HashMap;
import java.util.Map;

public class PitfallExample {
    public static void main(String[] args) {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("key", 1);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("key", 2);

        // Wrong: putAll overwrites value
        map1.putAll(map2);
        System.out.println("After putAll: " + map1); // Output: {key=2}

        // Right: merge sums values
        map1.put("key", 1); // reset
        map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));
        System.out.println("After merge: " + map1); // Output: {key=3}
    }
}
Output
After putAll: {key=2} After merge: {key=3}
📊

Quick Reference

Summary tips for merging HashMaps:

  • Use putAll() for simple merges where overwriting is acceptable.
  • Use merge() to combine values for duplicate keys with custom logic.
  • Always initialize the target map before merging.
  • Handle null values carefully to avoid exceptions.

Key Takeaways

Use putAll() to copy all entries from one HashMap to another, overwriting duplicates.
Use merge() with a BiFunction to combine values for duplicate keys safely.
Always initialize your target HashMap before merging to avoid errors.
Handle null values carefully when using merge() to prevent exceptions.
Choose the merge method based on whether you want to overwrite or combine values.