如何使用流在Java 8中按值范围进行分组 [英] How to group by range of values in Java 8 using streams

查看:1958
本文介绍了如何使用流在Java 8中按值范围进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个示例场景:

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

Imagine we have employee records like:

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

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

and so on. The goal is to calculate the average salary of different age groups (for instance between 21 and 30 and 31 to 40 and so on).

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

I want to do this using stream and I just cant get my head around how I need to use groupingBy to get this done. I am thinking maybe I need to define some sort of tuple age range. Any ideas?

推荐答案

以下代码可以为您提供所需的信息。关键是支持分组的收集器类。

The below code should give you what you are looking for. The key is "Collectors" class which support grouping.

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

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

The illustration assuming the salary is integer but easy to switch to double

完整的程序看起来像

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}

这篇关于如何使用流在Java 8中按值范围进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆