Use Collectors.groupingby to create a map to a set
Use Collectors.toSet()
as a downstream in groupingBy:
Map<Key, Set<Item>> map = items.stream()
.collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
You have to use a downstream collector like this:
Map<Key, Set<Item>> listMap = items.stream()
.collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));
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