Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Collectors.groupingby to create a map to a set

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

like image 366
simonalexander2005 Avatar asked Feb 25 '19 09:02

simonalexander2005


People also ask

How does collectors groupingBy work?

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.

How to group by using Java 8?

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.

What is collectors in Java?

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.


1 Answers

Use Collectors.toSet() as a downstream in groupingBy:

Map<Key, Set<Item>> map = items.stream()
            .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
like image 136
Ruslan Avatar answered Oct 08 '22 13:10

Ruslan