如何使用java 8 stream和lambda来flatMap一个groupingBy结果 [英] how to use java 8 stream and lambda to flatMap a groupingBy result

查看:1916
本文介绍了如何使用java 8 stream和lambda来flatMap一个groupingBy结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含其他对象列表的对象,我想返回由容器的某些属性映射的包含对象的平面图。是否有可能只使用流和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;
        }))));

这篇关于如何使用java 8 stream和lambda来flatMap一个groupingBy结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆