tkja tkja - 19 days ago 5x
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

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 = ->, x ->;

However, because there might be multiple POJOs with the same
, I want the value of the map be a
. All
Strings for the same key
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*;
... ->, mapping((x) ->, toSet())));