I know how to create a Map<T, List<U>>
, using Collectors.groupingBy
:
Map<Key, List<Item>> listMap = items.stream().collect(Collectors.groupingBy(s->s.key));
How would I modify that code to create Map<Key, Set<Item>>
? Or can I not do it using stream
and so have to create it manually using a for loop etc.?
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.
In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Java Collectors class provides various methods to deal with elements. Methods.
Use Collectors.toSet()
as a downstream in groupingBy:
Map<Key, Set<Item>> map = items.stream()
.collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With