You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Sorted Nested Stream 按食材最早日期排序菜谱实现问题

Java 嵌套Stream实现菜谱排序方案

前置依赖

你的Recipe和Ingredient类需要提供对应属性的getter方法,默认约定如下:

  • Recipe类:getTitle()获取菜谱标题,getIngredients()获取食材列表
  • Ingredient类:getBestBefore()获取食材保质期

实现代码

生成新排序后的列表

如果需要保留原列表不变,返回新的排序后列表可以用如下写法:

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public List<Recipe> sortRecipesByEarliestBestBefore(List<Recipe> allRecipes) {
    return allRecipes.stream()
        .sorted(Comparator.comparing(recipe -> 
            // 嵌套流计算当前菜谱所有食材的最小保质期
            recipe.getIngredients().stream()
                .map(Ingredient::getBestBefore)
                .min(Date::compareTo)
                // 无食材的菜谱兜底逻辑,默认排到列表最后,可根据业务调整兜底值
                .orElse(new Date(Long.MAX_VALUE))
        ))
        .collect(Collectors.toList());
}

原地排序

如果不需要保留原列表,直接原地排序可以简化写法:

allRecipes.sort(Comparator.comparing(recipe -> 
    recipe.getIngredients().stream()
        .map(Ingredient::getBestBefore)
        .min(Date::compareTo)
        .orElse(new Date(Long.MAX_VALUE))
));

逻辑说明

  1. 外层Stream遍历所有菜谱,通过sorted方法传入自定义比较器,默认按提取的key升序排列,符合最小日期靠前的需求
  2. 比较器的key提取逻辑通过嵌套Stream实现:遍历当前菜谱的所有食材,取出bestBefore属性后取最小值
  3. 对无食材的极端场景做了兜底处理,可根据业务需要调整兜底的日期值
  4. 用示例数据测试时,三个菜谱计算出的最小日期分别是Recipe1:2020、Recipe2:1999、Recipe3:1800,排序结果为Recipe3 → Recipe2 → Recipe1,和要求完全匹配

内容的提问来源于stack exchange,提问作者user1744750

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:12:00