我有一个对象列表,如下所示。如果任何成分超过了使用截止日期,则生成的列表不应包含食谱。这可以通过Java Streams实现吗。
我试着像下面这样做,但遇到了一个编译错误。非常感谢你的回复,因为我一直在努力寻找答案。
List<Recipes> filteredList =
recipeList.stream().filter(recipes -> recipes.getIngredients().stream().filter(ingredients -> ingredients.getUseBy().before(lunchDate)).collect(Collectors.toList()));
[
{
"id": 1,
"recipeName": "Pasta",
"createdDate": "2020-11-22T00:00:00.000+00:00",
"ingredients": [
{
"ingredientId": 1,
"ingredientName": "Shells",
"useBy": "2020-11-20",
"bestBefore": "2020-11-18"
},
{
"ingredientId": 2,
"ingredientName": "Mozaralla Cheese",
"useBy": "2020-12-20",
"bestBefore": "2020-11-23"
}
]
},
{
"id": 2,
"recipeName": "Burger",
"createdDate": "2020-11-22T00:00:00.000+00:00",
"ingredients": [
{
"ingredientId": 3,
"ingredientName": "Burger Bun",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
},
{
"ingredientId": 4,
"ingredientName": "Beef Pattie",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
},
{
"ingredientId": 5,
"ingredientName": "Tomato",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
}
]
},
{
"id": 3,
"recipeName": "Chicken Salad",
"createdDate": "2020-11-22T00:00:00.000+00:00",
"ingredients": [
{
"ingredientId": 6,
"ingredientName": "Salad Mix",
"useBy": "2020-12-20",
"bestBefore": "2020-11-15"
},
{
"ingredientId": 7,
"ingredientName": "Chicken",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
}
]
}
]
Stream().filter()
将Predicate<T>
作为参数,并返回由该流中与给定谓词匹配的元素组成的流。您的要求可以改写为:
List<Recipes> filteredList = recipeList.stream().filter(predicate: recipes does not contain any ingredient past useBy date).collect(Collectors.toList()));
您的问题被更改为编写匹配的谓词:配方不包含任何超过useBy
日期的成分。(对于任何配方,计算通过useBy
日期的成分,计数应为0。(
你可以使用另一个stream().filter(predicate: count ingredient after useBy date, and it should be 0)
recipes -> recipes.getIngredients().stream()
.filter(ingredients -> ingredients.getUseBy().after(lunchDate))
.collect(Collectors.toList()).size() == 0
然后将谓词添加到第一个筛选器表达式中。最后的表达式是这样的:
List<Recipes> filteredList = recipeList.stream().filter(
recipes -> recipes.getIngredients().stream()
.filter(ingredients -> ingredients.getUseBy().after(lunchDate))
.collect(Collectors.toList()).size() == 0
).collect(Collectors.toList()));
这里的工作示例(不使用JSON(。
考虑以下内容:
List<Recipe> filteredList =
recipes.stream()
.filter(r -> ! r.getIngredients()
.stream()
.anyMatch(i -> i.getUseBy().before(lunchDate)))
.collect(Collectors.toList());
每个配方的描述是:
- 获取配料
- 在
lunchDate
之前用useBy
查找任何"坏"成分 - 如果有任何"坏"成分,则排除(通过
!
运算符(配方