12

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

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92

3 Answers3

16

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

Map<Key, Set<Item>> map = items.stream()
            .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
Ruslan
  • 6,090
  • 1
  • 21
  • 36
4

You have to use a downstream collector like this:

Map<Key, Set<Item>> listMap = items.stream()
    .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
Naman
  • 27,789
  • 26
  • 218
  • 353
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
3

I also like the non-stream solution sometimes:

 Map<Key, Set<Item>> yourMap = new HashMap<>();
 items.forEach(x -> yourMap.computeIfAbsent(x.getKey(), ignoreMe -> new HashSet<>()).add(x));

If you really wanted you could exercise to do the same via compute/merge methods too

Eugene
  • 117,005
  • 15
  • 201
  • 306