In JDK9 there's new standard collector called flatMapping
which can be implemented in the following way:
public static <T, U, A, R>
Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper,
Collector<? super U, A, R> downstream) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return Collector.of(downstream.supplier(),
(r, t) -> {
try (Stream<? extends U> result = mapper.apply(t)) {
if (result != null)
result.sequential().forEach(u -> downstreamAccumulator.accept(r, u));
}
},
downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Collector.Characteristics[0]));
}
You can add it to your project and use like this:
operations.stream()
.filter(s -> s.getTotal() > 10)
.collect(groupingBy(Selling::getClientName,
flatMapping(s -> s.getProducts().stream(), toList())));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…