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

如何用Java 8 Stream替换for循环遍历嵌套Map实现条件筛选

Java 8 Stream 替换嵌套循环实现嵌套集合筛选

你可以用 Java 8 Stream 的 filter、anyMatch 和收集器替代原有嵌套循环,实现逻辑完全一致的功能,同时代码更简洁:

public Set<Integer> getValue(String input) {
    // 初始化数据(修正原代码中的笔误)
    Map<String, Boolean> in1 = new HashMap<>();
    in1.put("test_1", true);
    Map<String, Boolean> in2 = new HashMap<>();
    in2.put("test_2", false);
    Map<String, Boolean> in3 = new HashMap<>();
    in3.put("test_3", false);
    Map<String, Boolean> in4 = new HashMap<>();
    in4.put("test_4", true);
    
    List<Map<String, Boolean>> l1 = new ArrayList<>();
    l1.add(in1);
    l1.add(in2);
    List<Map<String, Boolean>> l2 = new ArrayList<>();
    l2.add(in3);
    l2.add(in4);
    
    Map<Integer, List<Map<String, Boolean>>> map = new HashMap<>();
    map.put(123, l1);
    map.put(345, l2);

    // Stream 核心实现逻辑
    return map.entrySet().stream()
            // 过滤:外层Map的Entry对应的List中,存在至少一个Map符合条件
            .filter(entry -> entry.getValue().stream()
                    .anyMatch(m -> m.containsKey(input) && Boolean.TRUE.equals(m.get(input))))
            // 提取符合条件的外层Map键
            .map(Map.Entry::getKey)
            // 收集为Set集合
            .collect(Collectors.toSet());
}

逻辑说明:

  1. 遍历外层Map:通过 map.entrySet().stream() 将外层Map的键值对转换为流;
  2. 过滤目标Entry:使用 filter 方法,对每个Entry的子集合List做判断——将List转为流后,用 anyMatch 检查是否存在至少一个Map满足「包含指定input键,且对应值为true」的条件(anyMatch 找到符合条件的元素后会停止遍历,效率和原循环一致);
  3. 提取键值:通过 map(Map.Entry::getKey) 将过滤后的Entry映射为外层的Integer键;
  4. 收集结果:用 Collectors.toSet() 将最终键收集为Set,与原逻辑返回类型一致。

注意事项:

  • 原代码存在笔误:in2.put("test_3", false) 和 in2.put("test_4", true) 应分别改为 in3.put(...) 和 in4.put(...),否则in3、in4会是空Map,无法触发对应条件;
  • 使用 Boolean.TRUE.equals(m.get(input)) 比直接写 m.get(input) == true 更规范,可避免潜在的null值问题(虽然此处因先判断了m.containsKey(input),get不会返回null,但该写法更通用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:05:32