For the sake of this example, let\'s assume I have a simple type Tuple
with two attributes:
interface Tuple {
T getFirst();
U ge
I found a solution; It involves Collections.mapping()
, which can wrap a collector and apply mapping function over stream to supply elements to the wrapped collector:
static <T, U> Map<T, Set<U>> groupSecondByFirst(Collection<Tuple<T, U>> tuples) {
return tuples
.stream()
.collect(
Collectors.groupingBy(
Tuple::getFirst,
Collectors.mapping(
Tuple::getSecond,
Collectors.toSet())));
}