Java 8流组由min和max组成 [英] Java 8 stream group by min and max

查看:201
本文介绍了Java 8流组由min和max组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您对employees表运行SQL查询:

Suppose you run an SQL query against an employees table:

SELECT department, team, MIN(salary), MAX(salary)
  FROM employees
 GROUP BY department, team

并且在java中客户端通过进行如下所示的DAO调用将结果集映射到 Aggregate 实例列表:

And in the java client you map the result set to a list of Aggregate instances by making a DAO call like below:

List<Aggregate> deptTeamAggregates = employeeDao.getMinMaxSalariesByDeptAndTeam()

并且'Aggregate'具有部门,团队,minSalary的getter方法, maxSalary,有一个对< T,T> 元组

And 'Aggregate' has getter methods for department, team, minSalary, maxSalary and there is a Pair<T, T> tuple

什么是最清晰的,可能是最优的将结果集映射到下面两个映射的方法:

What would be the clearest and possible the most optimal way to map the result set into the two maps below:

Map<String, Pair<Integer, Integer>> byDepartmentMinMax = ...
Map<Pair<String, String>, Pair<Integer, Integer>> byDepartmentAndTeamMinMax  = ...

我知道我可以用不同的方式映射我的结​​果集和/或制作两次访问数据库并以更简单的方式实现相同的目标但我更了解java 8的功能。

I know I could map my result set in a different way and/or make two trips to the database and achieve the same thing in an easier way but I am more about understanding the java 8 capabilities.

提前感谢您的输入。

推荐答案

    class Pair<T, U> {
        public final T x;
        public final U y;

        public Pair(T x, U y) {
            this.x = x;
            this.y = y;
        }
    }

    Collector<Aggregate, ?, Pair<Integer, Integer>> aggregateSalary = 
        mapping(a -> new Pair<>(a.getMinSalary(), a.getMaxSalary()),
            reducing(new Pair<>(Integer.MAX_VALUE, Integer.MIN_VALUE),
                (a, b) -> new Pair<>(Math.min(a.x, b.x), Math.max(a.y, b.y))));

    Map<String, Pair<Integer, Integer>> byDepartmentMinMax =
        deptTeamAggregates.stream()
            .collect(groupingBy(a -> a.getDepartment(), aggregateSalary));

    Map<Pair<String, String>, Pair<Integer, Integer>> byDepartmentAndTeamMinMax =
        deptTeamAggregates.stream()
            .collect(toMap(a -> new Pair<>(a.getDepartment(), a.getTeam()), a -> new Pair<>(a.getMinSalary(), a.getMaxSalary())));

这篇关于Java 8流组由min和max组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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