Java 8: Merging Two Maps Example

Merging two maps is a common task in Java, and Java 8 provides several ways to accomplish this using the 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

  1. Introduction
  2. Using putAll Method
  3. Using Stream API
  4. Using Map.merge Method
  5. 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

  • putAll method copies all entries from map2 to map1.
  • If map1 contains a key that is also in map2, the value from map2 overwrites the value in map1.

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.concat combines the entry streams of map1 and map2.
  • Collectors.toMap collects the combined stream into a new map.
  • The merge function (value1, value2) -> value1 + value2 handles 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 forEach method iterates over each entry in map2.
  • The merge method updates map1 with entries from map2.
  • The merge function Integer::sum handles 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