我有一个物品清单如下。如果任何成分超过使用日期,则最终列表不应包含配方。这是否可以通过java流实现。
我试图像下面这样做,但得到一个编译错误。非常感谢您的回复,因为我一直在努力寻找答案。
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"
}
]
}
]
2条答案
按热度按时间mgdq6dx11#
这里的工作示例(不使用json)。
考虑以下几点:
每个配方的说明如下:
去拿配料
找到任何“坏”的成分
useBy
之前lunchDate
排除(通过!
(操作员)如果有任何“坏”成分,请提供配方flvlnr442#
Stream().filter()
需要一个Predicate<T>
作为参数,并返回一个流,该流包含与给定 predicate 匹配的该流元素。您的要求可以重新表述为:您的问题被更改为编写匹配的 predicate :recipes不包含任何过去的成分
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 filteredList = recipeList.stream().filter(
recipes -> recipes.getIngredients().stream()
.filter(ingredients -> ingredients.getUseBy().after(lunchDate))
.collect(Collectors.toList()).size() == 0
).collect(Collectors.toList()));