tkja tkja - 2 months ago 15
Java Question

Java Stream Collectors.toMap value is a Set

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 = ???

Answer

groupingBy does exactly what you want:

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