Is there an aggregateBy method in the stream Java 8 api?

后端 未结 3 873

Run across this very interesting but one year old presentation by Brian Goetz - in the slide linked he presents an aggregateBy() method supposedly in the Stream

3条回答
  •  生来不讨喜
    2020-12-05 16:10

    Let's say we have a list of employees with their department and salary and we want the total salary paid by each department.

    There are several ways to do it and you could for example use a toMap collector to aggregate the data per department:

    • the first argument is the key mapper (your aggregation axis = the department),
    • the second is the value mapper (the data you want to aggregate = salaries), and
    • the third is the merging function (how you want to aggregate data = sum the values).

    Example:

    import static java.util.stream.Collectors.*;
    
    public static void main(String[] args) {
      List persons = Arrays.asList(new Person("John", "Sales", 10000),
                                           new Person("Helena", "Sales", 10000),
                                           new Person("Somebody", "Marketing", 15000));
    
      Map salaryByDepartment = persons.stream()
              .collect(toMap(Person::department, Person::salary, (s1, s2) -> s1 + s2));
      System.out.println("salary by department = " + salaryByDepartment);
    }
    

    As often with streams, there are several ways to get the desired result, for example:

    import static java.util.stream.Collectors.*;
    
    Map salaryByDepartment = persons.stream()
            .collect(groupingBy(Person::department, summingDouble(Person::salary)));
    

    For reference, the Person class:

    static class Person {
      private final String name, department;
      private final double salary;
      public Person(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
      }
      public String name() { return name; }
      public String department() { return department; }
      public double salary() { return salary; }
    }
    

提交回复
热议问题