tkja tkja - 1 year ago 102
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 = ???

Answer Source

groupingBy does exactly what you want:

import static*;
... ->, mapping((x) ->, toSet())));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download