我在下面列出了对象,并且需要根据日期之前的成分对其进行排序。因此,日期最久的食谱应该排在最后。
[
{
"id": 2,
"recipeName": "Burger",
"createdDate": "2020-11-22T00:00:00.000+00:00",
"ingredients": [
{
"ingredientId": 3,
"ingredientName": "Burger Bun",
"category": "",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
},
{
"ingredientId": 4,
"ingredientName": "Beef Pattie",
"category": "",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
},
{
"ingredientId": 5,
"ingredientName": "Tomato",
"category": "",
"useBy": "2020-12-20",
"bestBefore": "2020-09-10"
}
]
},
{
"id": 3,
"recipeName": "Chicken Salad",
"createdDate": "2020-11-22T00:00:00.000+00:00",
"ingredients": [
{
"ingredientId": 7,
"ingredientName": "Chicken",
"category": "",
"useBy": "2020-12-20",
"bestBefore": "2020-12-23"
},
{
"ingredientId": 6,
"ingredientName": "Salad Mix",
"category": "",
"useBy": "2020-12-20",
"bestBefore": "2020-11-15"
}
]
}
]
我已经尝试过下面的代码,但是它只是对配方中的配料进行排序,而不是列表中的配方对象。Java 8 Streams是否可以实现?
List<Recipes> finalList = filteredList.stream().sorted((o1, o2) -> (int) (o1.getId() - o2.getId()))
.map(recipes -> {
List<Ingredients> in = recipes.getIngredients().stream()
.sorted(Comparator.comparing(Ingredients::getBestBefore).reversed()).collect(Collectors.toList());
recipes.setIngredients(in);
return recipes;
}).collect(Collectors.toList());
由于您需要确保任何成分的历史最悠久bestBefore
,因此该食谱应排在列表的最后。您可能需要max
在配方的成分中标识(最早的)日期,为此可以创建如下方法:
private static Date findOldestBestBeforeForRecipe(Recipes recipes) {
return recipes.getIngredients()
.stream()
.map(Ingredients::getBestBefore)
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalArgumentException("recipes without ingredients!!"));
}
然后对您的配方进行排序,将可以简化操作,例如Comparator<Recipes>
为此条件定义a并将其附加到现有比较中。
Comparator<Recipes> ingredientsBestBeforeDate = (o1, o2) ->
findOldestBestBeforeForRecipe(o2).compareTo(findOldestBestBeforeForRecipe(o1));
List<Recipes> finalList = filteredList.stream()
.sorted(Comparator.comparingInt(Recipes::getId)
.thenComparing(ingredientsBestBeforeDate))
.collect(Collectors.toList());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句