问题描述
示例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 onlyProduct
s with active types (whatever that means).
这篇关于列表过滤器中的Java 8 Lambda列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!