列表过滤器中的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"
      }
    ]
  }
]

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

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

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

因为您没有显示太多代码,所以这将是黑暗中的一枪。我的主要建议是在Stream<ProductResponse>将其Stream<List<Product>>收集到列表之前不要将其映射

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

如果要包含具有有效类型的s,可以更改anyMatchallMatchList<ProductResponse>Product

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章