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

如何使用Java 8 Stream遍历多级Map并按分类打印结果

实现方案

你生成的是两级嵌套Map结构,用Stream遍历的核心是逐层处理entrySet,如果需要扁平化处理所有元素可以用flatMap打平结构,以下是可直接替换到你main方法中的实现:

1. 结构化层级打印(保留分类关系)

// 替换你原代码中的 System.out.println(dishesByTypeCaloricLevel); 即可
dishesByTypeCaloricLevel.entrySet().stream()
    .forEach(typeEntry -> {
        System.out.printf("===== 菜品类型:%s =====%n", typeEntry.getKey());
        typeEntry.getValue().entrySet().stream()
            .forEach(levelEntry -> {
                String dishNames = levelEntry.getValue().stream()
                    .map(DishDiet::getName)
                    .toList()
                    .toString();
                System.out.printf("热量等级:%s | 菜品列表:%s%n", levelEntry.getKey(), dishNames);
            });
        System.out.println();
    });

2. 扁平化遍历(提取所有菜品统一处理)

如果不需要保留层级关系,只需要拿到所有分类后的菜品,可以用flatMap把多级结构打平为单一流:

List<DishDiet> allClassifiedDishes = dishesByTypeCaloricLevel.values().stream()
    // 打平第一级Map,获取所有二级Map的value
    .flatMap(levelMap -> levelMap.values().stream())
    // 打平第二级Map的List,获取所有DishDiet对象
    .flatMap(List::stream)
    .toList();

// 示例:打印所有菜品名
System.out.println("所有分类菜品:" + allClassifiedDishes.stream().map(DishDiet::getName).toList());

原代码优化提示

你已经在DishDiet实体类中定义了caloricLevel字段,生成分类Map时不需要重复判断热量阈值,直接改用方法引用即可简化代码:

// 原来的分组逻辑可简化为:
Map<DishDiet.Type, Map<DishDiet.CaloricLevel, List<DishDiet>>> dishesByTypeCaloricLevel = getAllDishDiet()
    .stream()
    .collect(Collectors.groupingBy(
        DishDiet::getType,
        Collectors.groupingBy(DishDiet::getCaloricLevel)
    ));

注意要提前导入Collectors的静态方法:import static java.util.stream.Collectors.groupingBy; 避免编译报错


内容的提问来源于stack exchange,提问作者Er Rahul Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:36:06