How to Construct a new Map using List of Maps using Java 8 streams

In this post, we will see how to Construct a new Map using List of Maps using Java 8 streams. Here’s an example of how to construct a new map using a List of Maps in Java 8 streams.

import java.util.*;
import java.util.stream.Collectors;

public class MapListExample {
    public static void main(String[] args) {
        // Create a list of maps
        List<Map<String, String>> listOfMaps = new ArrayList<>();

        Map<String, String> map1 = new HashMap<>();
        map1.put("name", "John");
        map1.put("age", "30");

        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "Alice");
        map2.put("age", "25");

        listOfMaps.add(map1);
        listOfMaps.add(map2);

        // Use Java 8 streams to construct a new map
        Map<String, String> resultMap = listOfMaps.stream()
                .collect(Collectors.toMap(
                        // Key mapper function (using "name" as the key)
                        map -> map.get("name"),
                        // Value mapper function (using "age" as the value)
                        map -> map.get("age"),
                        // Merge function (if there are duplicate keys)
                        (existing, replacement) -> existing));

        // Print the resulting map
        resultMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Output:

John: 30
Alice: 25

In this example, we start with a List of Map objects, where each Map represents a person’s information with keys like “name” and “age.” We use Java 8 streams to transform this list into a new Map called resultMap where the “name” is used as the key, and “age” is used as the value. If there are duplicate keys (which we handle with the merge function), the existing value is kept. Finally, we print the resulting resultMap.

That’s all about How to Construct a new Map using List of Maps using Java 8 streams.

Other Java 8 tutorials.