如何使用流在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)
- 将基于Spring的Spring转换为基于Java的配置
- 使用多个线程的JPA持久性
- 基于磁盘的HashMap
- 单个模块的Maven配置文件
- 将带有网格线的jTable行复制到excel / word文档中
- Spring Batch,JdbcExecutionContextDao java.util.Map $ Entry deserializer issue,xstream 1.4.1
- Struts 1使用Multipart / Form-Data Enctype进行失败的表单validation后丢失请求参数
- 使用分隔每个条目的线条在toString中打印Arraylist
- 如何通过JNDI检索LDAP密码