Use Collectors.groupingby to create a map to a set

  • A+
Category:Languages

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

 


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

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: