Java 8流组由min和max组成

时间:2015-06-20 20:22:44

标签: java java-8 java-stream

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

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

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

List<Aggregate> deptTeamAggregates = employeeDao.getMinMaxSalariesByDeptAndTeam()

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

将结果集映射到下面两张地图中最清晰,最可能的最佳方法是什么:

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

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

提前感谢您的意见。

1 个答案:

答案 0 :(得分:4)

    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())));