如何使用 java 8 流和 lambda 来 flatMap 一个 groupingBy 结果

2022-01-22 00:00:00 lambda java-8 java java-stream collectors

我有一个包含其他对象列表的对象,我想返回由容器的某些属性映射的包含对象的平面图.是否可以仅使用流和 lambdas?

I have a object with contains a list of other objects and I want to return a flatmap of the contained objects mapped by some property of the container. Any one if is it possible using stream and lambdas only?

public class Selling{
   String clientName;
   double total;
   List<Product> products;
}

public class Product{
   String name;
   String value;
}

让我们假设一个操作列表:

Lets supose a list of operations:

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>>

推荐答案

你可以试试这样的:

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;
        }))));

相关文章