Mapping, aggregating and composing totals using Java 8 Streams
You can use the toMap
collector as follows:
Collection<OrderTotal> result = orders.stream()
.map(o -> createFromOrder(o))
.collect(toMap(Function.identity(),
Function.identity(),
(l, r) -> {
aggregate(l, r);
return l;
}))
.values();
Note that this requires changing the aggregate
method parameters to aggregate(OrderTotal orderTotal, OrderTotal order){ ... }
i.e. both parameters are of type OrderTotal
.
or you could remove the aggregate
method entirely and perform the logic in the toMap
:
Collection<OrderTotal> result = orders.stream()
.map(o -> createFromOrder(o))
.collect(toMap(Function.identity(),
Function.identity(),
(l, r) -> {
l.setTotalQty(l.getTotalQty() + r.getTotalQty());
l.setTotalValue(l.getTotalValue() + r.getTotalValue());
return l;
}))
.values();
you could do something like this -
Double totalQtyAgg = orders.stream()
.map(x -> createFromOrder(x))
.mapToDouble(x -> x.totalQty)
.sum();
Double totalValueAgg = orders.stream()
.map(x -> createFromOrder(x))
.mapToDouble(x -> x.totalValue)
.sum();