Java 8 Lambda-分组和归约对象

问题描述 投票:0回答:1

我有一个我想要的交易清单:

  • 按年份分组
  • 然后按该年中每笔交易的类型分组
  • 然后将事务转换为具有子组中所有事务的值之和的Result对象。

我的代码段看起来像:

Map<Integer, Map<String, Result> res = transactions.stream().collect(Collectors
                            .groupingBy(Transaction::getYear,
                                groupingBy(Transaction::getType),
                                  reducing((a,b)-> new Result("YEAR_TYPE", a.getAmount() + b.getAmount()))
));

交易类:

class Transaction {

    private int year;
    private String type;
    private int value;
}

结果类:

class Result {

    private String group;
    private int amount;
}

它似乎不起作用,我应该怎么做才能解决此问题,以确保它也适用于并行流?

lambda java-8 stream collectors
1个回答
0
投票
Collector<Transaction, Result, Result> resultCollector = Collector.of(() -> new Result(), // what is the result of this collector (a, b) -> { a.setAmount( a.getAmount() + b.getValue()); a.setGroup(b.getType()); }, // how to combine a result and a transaction (l, r) -> { l.setAmount(l.getAmount() + r.getAmount()); return l; }); // how to combine two // result instances // (used in parallel streams)

然后您可以使用收集器来获取地图:

Map<Integer, Map<String, Result>> collect = transactions.parallelStream().collect(
       groupingBy(Transaction::getYear,
               groupingBy(Transaction::getType, resultCollector) ) );
© www.soinside.com 2019 - 2024. All rights reserved.