Java Stream Collectors.toMap value is a collection

I want to use Java Stream to run over a POJO list, such as List<A> below, and convert it to Map Map<String, Set<String>> .

For example, class A:

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

I wrote the code below that collects 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, since there may be several POJOs with the same name , I want the map value to be Set . All property Lines for the same name key must go into the same set.

How can I do that?

 // 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 = ??? 
+7
java java-8 java-stream
source share
3 answers

groupingBy does exactly what you want:

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

Alternatively, you can use the merge function of the Collectors.toMap Collectors.toMap function (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); 
+1
source share

@ The answer to nevay is certainly the right way using groupingBy , but it is also possible toMap by adding 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 an array to a map with a key like x.name and a HashSet value with one x.property value. When there is a duplicate key / value, the merge function of the third parameter is then called to combine the two HashSets.

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

0
source share

All Articles