[英]Java 8 lambda list inside list filter
Sample JSON 样本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. 我想检索具有至少一个活动产品的对象列表。
Below code returns list of products but I want a list of ProdcutResponse
. 下面的代码返回产品列表,但我需要ProdcutResponse
列表。 Any way to do this? 有什么办法吗?
response.stream()
.map(ProductResponse::getProducts)
.filter(s -> "Active".equals(s.getType()))
.collect(Collectors.toList())
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: 我的主要建议是在将其收集到列表之前,不要将Stream<ProductResponse>
映射到Stream<List<Product>>
:
response.stream()
.filter(pr -> pr.getProducts().stream().anyMatch(s -> "Active".equals(s.getType())))
.collect(Collectors.toList());
You can change anyMatch
to allMatch
if you want the List<ProductResponse>
to contain only Product
s with active types (whatever that means). 如果您希望List<ProductResponse>
仅包含具有活动类型的Product
(无论如何),则可以将anyMatch
更改为allMatch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.