Map values in Collectors.groupingBy()

后端 未结 1 852
终归单人心
终归单人心 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  Map> groupSecondByFirst(Collection> tuples) {
        return tuples
            .stream()
            .collect(
                Collectors.groupingBy(
                    Tuple::getFirst,
                    Collectors.mapping(
                        Tuple::getSecond,
                        Collectors.toSet())));
    }
    

    0 讨论(0)
提交回复
热议问题