我有一个我想要的交易清单:
我的代码段看起来像:
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;
}
它似乎不起作用,我应该怎么做才能解决此问题,以确保它也适用于并行流?
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) ) );