如何使用流在Java 8中按值范围进行分组

kap*_*tan 4 java java-8

以下是一个示例场景:

想象一下,我们有员工记录,如:

name, age, salary (in 1000 dollars)
   a,  20,     50
   b,  22,     53
   c,  34,     79
Run Code Online (Sandbox Code Playgroud)

等等.目标是计算不同年龄组的平均工资(例如21至30岁和31至40岁等).

我想用这个来做stream,我只是无法理解我需要用它groupingBy来完成这项工作.我想也许我需要定义某种元组年龄范围.有任何想法吗?

Bas*_*ski 7

以下代码应该为您提供所需的内容.关键是支持分组的"收藏家"类.

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

假设工资是整数但很容易切换到双倍的插图

完整的程序看起来像

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;

}
Run Code Online (Sandbox Code Playgroud)

输出是

{4.0=200, 2.0=100, 3.0=100}
Run Code Online (Sandbox Code Playgroud)


Dav*_* L. 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)
Run Code Online (Sandbox Code Playgroud)