[英]how to use java 8 stream and lambda to flatMap a groupingBy result
我有一個包含其他對象列表的對象,我想返回由容器的某些屬性映射的包含對象的平面圖。 任何一個是否可以只使用流和lambdas?
public class Selling{
String clientName;
double total;
List<Product> products;
}
public class Product{
String name;
String value;
}
讓我們來處理一系列操作:
List<Selling> operations = new ArrayList<>();
operations.stream()
.filter(s -> s.getTotal > 10)
.collect(groupingBy(Selling::getClientName, mapping(Selling::getProducts, toList());
結果將是善意的
Map<String, List<List<Product>>>
但我想像它一樣扁平化
Map<String, List<Product>>
在JDK9中有一個名為flatMapping
的新標准收集器,它可以通過以下方式實現:
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]));
}
您可以將它添加到您的項目並使用如下:
operations.stream()
.filter(s -> s.getTotal() > 10)
.collect(groupingBy(Selling::getClientName,
flatMapping(s -> s.getProducts().stream(), toList())));
你可以嘗試類似的東西:
Map<String, List<Product>> res = operations.parallelStream().filter(s -> s.getTotal() > 10)
.collect(groupingBy(Selling::getClientName, mapping(Selling::getProducts,
Collector.of(ArrayList::new, List::addAll, (x, y) -> {
x.addAll(y);
return x;
}))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.