Java 8 grouping using custom collector?

后端 未结 3 1157
鱼传尺愫
鱼传尺愫 2020-11-30 11:52

I have the following class.

class Person {

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
             


        
3条回答
  •  青春惊慌失措
    2020-11-30 12:16

    When grouping a Stream with Collectors.groupingBy, you can specify a reduction operation on the values with a custom Collector. Here, we need to use Collectors.mapping, which takes a function (what the mapping is) and a collector (how to collect the mapped values). In this case the mapping is Person::getName, i.e. a method reference that returns the name of the Person, and we collect that into a List.

    Map> collect = 
        members.stream()
               .collect(Collectors.groupingBy(
                   Person::getAge,
                   Collectors.mapping(Person::getName, Collectors.toList()))
               );
    

提交回复
热议问题