I am trying to get following Map via Java 8
Class One {
String one;
List two;
}
Class Two {
BigDecimal bd;
}
How do I collect a Map which contains grouping by One.one i.e., first parameter of map. For second parameter of map sum of Two.bd.
解决方案
You can use this:
List list = ...;
Map result1 = list.stream()
.collect(Collectors.groupingBy(One::getOne, // key is One.one
Collectors.mapping(one -> one.getTwo().stream() // get stream of One.two
.map(Two::getBd) // map to Bd
.reduce(BigDecimal.ZERO, BigDecimal::add), // reduce to sum
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add) // sum sums
)
));
This will sum all the bd of Two, and then also sum the sums for Ones that have the same one.
Although things would be simpler if Java8 had a flatMapping collector, one has been added to Java9:
public static
Collector flatMapping(Function super T, ? extends Stream extends U>> mapper,
Collector super U, A, R> downstream) {
BiConsumer downstreamAccumulator = downstream.accumulator();
return Collector.of(downstream.supplier(),
(r, t) -> mapper.apply(t).sequential().forEach(u -> downstreamAccumulator.accept(r, u)),
downstream.combiner(),
downstream.finisher(),
downstream.characteristics().stream().toArray(Collector.Characteristics[]::new));
}
Which would make:
Map result1 = list.stream()
.collect(Collectors.groupingBy(One::getOne,
flatMapping(one -> one.getTwo().stream().map(Two::getBd),
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)
)
));