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

以下是一个示例场景:

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

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

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

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

以下代码应该为您提供所需的内容。 关键是支持分组的“collections家”类。

 Map 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 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 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} 

是的,您可以定义AgeGroup接口甚至是这样的enum (假设为Employee定义):

 enum AgeGroup { TWENTIES, THIRTIES, FORTIES, FIFTIES; ..... } Function employee2Group = e -> { if(e.age >= 20 && e.getAge() < 30) return AgeGroup.TWENTIES; .... return null; }; Map avgByAgeGroup = employees.stream() .collect(Collectors.groupingBy(employee2Group, Collectors.averagingInt(Employee::getSalary))); avgByAgeGroup.get(AgeGroup.TWENTIES)