Java 8 grouping using custom collector?

后端 未结 3 1154
鱼传尺愫
鱼传尺愫 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 11:58

    You can also use Collectors.toMap and provide mapping for key, value and merge function(if any).

    Map<Integer, String> ageNameMap = 
        members.stream()
                .collect(Collectors.toMap(
                  person -> person.getAge(), 
                  person -> person.getName(), (pName1, pName2) -> pName1+"|"+pName2)
        );
    
    0 讨论(0)
  • 2020-11-30 12:09

    You can use a mapping Collector to map the list of Person to a list of person names :

    Map<Integer, List<String>> collect = 
        members.stream()
               .collect(Collectors.groupingBy(Person::getAge,
                                              Collectors.mapping(Person::getName, Collectors.toList())));
    
    0 讨论(0)
  • 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<Integer, List<String>> collect = 
        members.stream()
               .collect(Collectors.groupingBy(
                   Person::getAge,
                   Collectors.mapping(Person::getName, Collectors.toList()))
               );
    
    0 讨论(0)
提交回复
热议问题