How to group by value range in Java 8 using streams

Here is an example script:

Imagine that we have employee records, for example:

name, age, salary (in 1000 dollars)
   a,  20,     50
   b,  22,     53
   c,  34,     79

etc. The goal is to calculate the average salary of different age groups (for example, from 21 to 30 and from 31 to 40, etc.).

I want to do this with help stream, and I just can't figure out how I need to use groupingByto do this. I think maybe I need to determine some age range. Any ideas?

+4
source share
2 answers

The code below should indicate what you are looking for. The key is the Collectors class, which supports grouping.

Map<Double,Integer> ageGroup= employees.stream().collect(Collectors.groupingBy(e->Math.ceil(e.age/10.0),Collectors.summingInt(e->e.salary)));

, , ,

public static void main(String[] args) {
    // TODO Auto-generated method stub

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee("a",20,100));
    employees.add(new Employee("a",21,100));
    employees.add(new Employee("a",35,100));
    employees.add(new Employee("a",32,100));


    Map<Double,Integer> ageGroup= employees.stream().collect(Collectors.groupingBy(e->Math.ceil(e.age/10.0),Collectors.summingInt(e->e.salary)));
    System.out.println(ageGroup);
}

public static class Employee {
    public Employee(String name, int age, int salary) {
        super();
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    public String name;
    public int age;
    public int salary;

}

{4.0=200, 2.0=100, 3.0=100}
+5

, AgeGroup enum, ( Employee):

enum AgeGroup {
    TWENTIES,
    THIRTIES,
    FORTIES,
    FIFTIES;
    .....
}
Function<Employee, AgeGroup> employee2Group = e -> {
    if(e.age >= 20 && e.getAge() < 30)
        return AgeGroup.TWENTIES;
    ....
    return null;
};

Map<AgeGroup, Double> avgByAgeGroup = employees.stream()
    .collect(Collectors.groupingBy(employee2Group, Collectors.averagingInt(Employee::getSalary)));

avgByAgeGroup.get(AgeGroup.TWENTIES)
+2

Source: https://habr.com/ru/post/1614538/


All Articles