Search code examples
javasetjava-streamgrouping

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


Solution

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

    Map<Key, Set<Item>> map = items.stream()
                .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));