Map values in Collectors.groupingBy()

后端 未结 1 851
终归单人心
终归单人心 2021-02-12 15:27

For the sake of this example, let\'s assume I have a simple type Tuple with two attributes:

interface Tuple {
    T getFirst();
    U ge         


        
相关标签:
1条回答
  • 2021-02-12 15:55

    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())));
    }
    
    0 讨论(0)
提交回复
热议问题