Java Stream Collectors.toMap value is a Set

collectors.tomap object as value
collectors.tomap duplicate key
collectors.tomap treemap
collectors.tomap multiple keys
java 8 groupingby(map values)
java stream collect into a map
java collectors
list to map java 8

I want to use a Java Stream to run over a List of POJOs, such as the list List<A> below, and transform it into a Map Map<String, Set<String>>.

For example, class A is:

class A {
    public String name;
    public String property;
}

I wrote the code below that collects the values into a map Map<String, String>:

final List<A> as = new ArrayList<>();
// the list as is populated ...

// works if there are no duplicates for name
final Map<String, String> m = as.stream().collect(Collectors.toMap(x -> x.name, x -> x.property));

However, because there might be multiple POJOs with the same name, I want the value of the map be a Set. All property Strings for the same key name should go into the same set.

How can this be done?

// how do i create a stream such that all properties of the same name get into a set under the key name
final Map<String, Set<String>> m = ???

groupingBy does exactly what you want:

import static java.util.stream.Collectors.*;
...
as.stream().collect(groupingBy((x) -> x.name, mapping((x) -> x.property, toSet())));

Java 8 Collectors toMap, Collect a Java Stream to an Immutable Collection. Learn how to collect With toMap, we can indicate strategies for how to get the key and value for the map: ? The static overloaded methods, Collectors.toMap() return a Collector which produces a new instance of Map, populated with keys per provided keyMapper function and values per provided valueMap function.


@Nevay 's answer is definitely the right way to go by using groupingBy, but it is also achievable by toMap by adding a mergeFunction as the third parameter:

as.stream().collect(Collectors.toMap(x -> x.name, 
    x -> new HashSet<>(Arrays.asList(x.property)), 
    (x,y)->{x.addAll(y);return x;} ));

This code maps the array to a Map with a key as x.name and a value as HashSet with one value as x.property. When there is duplicate key/value, the third parameter merger function is then called to merge the two HashSet.

PS. If you use Apache Common library, you can also use their SetUtils::union as the merger

Collectors toMap() method in Java with Examples, The Collectors class is under the java.util.streams package. The task of the function is to merge the values having the same key in a way defined by the coder. A basic toMap method takes a key mapper and a value mapper. These are Java 8 Functions. These functions are used to derive the key and value. An input element from the stream is passed to the keyMapper. The output of that mapper will be used as the map key. Similarly, the valueMapper is used to derive the map value from the input. Collectors.toMap – Overloads Merge function. A couple of overloads exist for the toMap method.


Same Same But Different

Map<String, Set<String>> m = new HashMap<>();

as.forEach(a -> {
    m.computeIfAbsent(a.name, v -> new HashSet<>())
            .add(a.property);
    });

Java 8 Streams - Collectors.toMap Examples, java.lang.Object java.util.stream.Collectors LogicBig. The static overloaded of Map, populated with keys per provided keyMapper function and values per Java Collections - Only put Map key/value if the specified key does not exist · Getting  1. Stream Elements with unique map keys – Collectors.toMap() If the stream elements have the unique map key field then we can use Collectors.toMap() to collect elements to map in Map<keyObj, Element> format easily. For example, we can collect a list of Employee objects to map in where employee ids are unique fields and used a key to map entries.


Also, you can use the merger function option of the Collectors.toMap function Collectors.toMap(keyMapper,valueMapper,mergeFunction) as follows:

final Map<String, String> m = as.stream()
                                .collect(Collectors.toMap(
                                          x -> x.name, 
                                          x -> x.property,
                                          (property1, property2) -> property1+";"+property2);

java.util.stream.Collectors.toMap java code examples, Stream.collect · Set.stream · Map.entrySet · Map.Entry.getValue · List.stream Given two maps (A, B), returns all the key-value pairs in A whose keys are not  In this quick tutorial, we're going to talk about the toMap () method of the Collectors class. We'll use it to collect Stream s into a Map instance. For all the examples covered in here, we'll use a list of books as a starting point and transform it into different Map implementations. We'll start with the simplest case, by transforming a List


Collectors (Java Platform SE 8 ), Set<String> set = people.stream().map(Person::getName).collect(Collectors. Collector , and organizes them into a Map<Boolean, D> whose values are the  Java 8 provides Collectors.toMap() that is useful to convert List to Map. We need to pass mapping function for key and value. We need to pass mapping function for key and value. To avoid conflict of duplicate keys, we pass merge function otherwise it will throw IllegalStateException .


Java 8 Collectors toMap with Examples, In this blog post, I will demonstrate the Java 8 Collectors.toMap method with Examples include finding the sum or minimum of a set of numbers. A basic toMap method takes a key mapper and a value mapper. These are  3.Collectors.toMap() Since Stream is a sequence of items, in order to construct a Map out of it, we need specify how to extract keys/values pairs from it. The Collectors.toMap() returns a Collector that collects all the input elements into a new Map by applying the specified mapping functions to the input elements, which help in identifying the


Java 8 Convert List to Map using Collectors.toMap() Example, We need to pass mapping function for key and value. To avoid conflict  In this post, we will see how to convert List to Map using Stream in java 8. Collectors’s toMap can be used with Stream to convert List to Map in java.