列表过滤器中的Java 8 Lambda列表 [英] Java 8 lambda list inside list filter

查看:55
本文介绍了列表过滤器中的Java 8 Lambda列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例JSON

[
  {
    "id": "1",
    "products": [
      {
        "id": "333",
        "status": "Active"
      },
      {
        "id": "222",
        "status": "Inactive"
      },
      {
        "id": "111",
        "status": "Active"
      }

    ]
  },
  {
    "id": "2",
    "products": [
      {
        "id": "6",
        "status": "Active"
      },
      {
        "id": "7",
        "status": "Inactive"
      }
    ]
  }
]

我想检索具有至少一个活动产品的对象列表.

I want to retrieve list of objects that have at least one active product.

下面的代码返回产品列表,但我想要一个ProdcutResponse列表.有什么办法吗?

Below code returns list of products but I want a list of ProdcutResponse. Any way to do this?

 response.stream()
 .map(ProductResponse::getProducts)
 .filter(s -> "Active".equals(s.getType()))
 .collect(Collectors.toList()) 

推荐答案

由于您没有显示太多代码,因此这是黑暗中的一幕.我的主要建议是在将Stream<ProductResponse>映射到Stream<List<Product>>之前,不要将其映射到列表:

Because you didn't show much code, this will be a shot in the dark. My main suggestion would be to not map the Stream<ProductResponse> to a Stream<List<Product>> before collecting it to a list:

response.stream()
        .filter(pr -> pr.getProducts().stream().anyMatch(s -> "Active".equals(s.getType())))
        .collect(Collectors.toList());

如果希望List<ProductResponse>仅包含具有有效类型(无论如何)的 Product,则可以将anyMatch更改为allMatch.

You can change anyMatch to allMatch if you want the List<ProductResponse> to contain onlyProducts with active types (whatever that means).

这篇关于列表过滤器中的Java 8 Lambda列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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