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

如何使用Lambda表达式判断嵌套Map中是否存在TRUE值

使用Lambda表达式实现嵌套Map的布尔值判断

你可以借助Java Stream API结合Lambda表达式来简化这个逻辑,实现代码如下:

Map<String, Map<String, Boolean>> maps = new HashMap<>();
Map<String, Boolean> test = new HashMap<>();
test.put("test1", Boolean.FALSE);
test.put("test2", Boolean.TRUE);
maps.put("hey", test);
Map<String, Boolean> testtt = new HashMap<>();
testtt.put("test3", Boolean.FALSE);
testtt.put("test4", Boolean.TRUE);
maps.put("lol", testtt);

// Lambda+Stream实现逻辑
boolean hasTrue = maps.values().stream()
        .flatMap(innerMap -> innerMap.values().stream())
        .anyMatch(Boolean.TRUE::equals);

System.out.println(hasTrue);

逻辑说明:

  • maps.values().stream():将外层Map中所有的内层Map转换为Stream流
  • .flatMap(innerMap -> innerMap.values().stream()):把每个内层Map的布尔值集合展开成一个单一的布尔值流,相当于把两层嵌套的结构“拍平”
  • .anyMatch(Boolean.TRUE::equals):该方法是短路操作,只要在流中找到第一个true就会立即停止遍历,和你原来循环里的break逻辑完全一致,避免不必要的遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:01:54