Java中过滤HashMap需先调用entrySet().stream()获取Entry流,再用filter()按键(e.getKey())或值(e.getValue)筛选,注意null安全;可forEach遍历或collect转新Map,支持Predicate.not()提升可读性。

Java 中对 HashMap 使用 Stream 流过滤,核心是把 entrySet() 转成流,再用 filter() 筛选符合条件的键值对,最后可选择遍历或收集为新 Map。
获取 Entry 流并过滤
HashMap 本身不直接提供 stream() 方法,必须先调用 entrySet().stream() 得到 Stream<map.entry v>></map.entry>。这是所有操作的前提。
- 要按键过滤:用
entry.getKey()判断,比如排除 key 为".ABC"的项,写法是.filter(e -> !".ABC".equals(e.getKey())) - 要按值过滤:用
entry.getValue()判断,比如保留 value 大于 3 的项,写法是.filter(e -> e.getValue() > 3) - 注意 null 安全:推荐用
"固定字符串".equals(entry.getKey()),而不是entry.getKey().equals("固定字符串"),避免空指针异常
常见过滤场景示例
假设有一个 Map<string integer> map = new HashMap();</string>,含 {"Apple":2, "Banana":5, "Orange":3, "Grapes":4}:
- 只处理 value ≥ 4 的项:
map.entrySet().stream().filter(e -> e.getValue() >= 4).forEach(e -> System.out.println(e.getKey())) - 跳过以点开头的 key(如
".tmp"):.filter(e -> !e.getKey().startsWith(".")) - 同时满足多个条件:
.filter(e -> e.getValue() > 2 && e.getKey().length() > 4)
收集结果回新 HashMap
如果需要把过滤后的结果存成新 Map,要用 collect(Collectors.toMap()):
立即学习“Java免费学习笔记(深入)”;
- 基础写法:
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) - 处理键冲突(如原 Map 有重复 key 可能性):
(e1, e2) -> e1表示保留第一个 - 保持插入顺序(需 LinkedHashMap):
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2)->e1, LinkedHashMap::new)
进阶写法提升可读性
频繁做“排除”类过滤时,可用 Predicate.not() 让意图更清晰:
- 静态导入:
import static java.util.function.Predicate.not; - 替代写法:
.filter(not(e -> ".ABC".equals(e.getKey()))),语义即“不匹配 .ABC 的才留下” - 支持链式组合,例如
filter(not(isDotKey).and(isValidValue))


















