遍历 java hashmap 的所有键值对,最推荐的做法是使用增强型 for 循环配合 entryset()。这种方式直接获取键值对的映射关系,避免了通过键去重新查找值的开销,是处理大量数据时性能最优且代码最简洁的方案。

如何高效获取并修改 Map 中的值
在需要同时访问键和值,或者需要根据条件修改值时,使用 entrySet() 的迭代器或增强循环是唯一正确的选择。如果仅使用 keySet() 遍历键,然后在循环体内调用 get(key),不仅代码冗余,还会因为哈希表的二次查找导致性能下降。此外,若需在遍历过程中移除元素,必须使用迭代器的 remove() 方法,否则抛出 ConcurrentModificationException。

import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<string integer> map = new HashMap();
map.put("A", 1);
map.put("B", 2);
// 高效遍历并打印
for (Map.Entry<string integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// 安全地移除值为 1 的条目
map.entrySet().removeIf(entry -> entry.getValue() == 1);
}
}</string></string>
Java 8+ 函数式遍历与过滤
从 Java 8 开始,可以使用 forEach 结合 Lambda 表达式来简化遍历逻辑。这种方法代码更紧凑,特别适合执行简单的操作如打印或累加。如果需要基于条件筛选特定的键值对,可以结合 entrySet().stream() 进行链式调用,实现过滤、映射和收集,这在处理复杂业务逻辑时比传统循环更具可读性。

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<string integer> map = new HashMap();
map.put("X", 10);
map.put("Y", 20);
// 使用 forEach 打印
map.forEach((k, v) -> System.out.println(k + ": " + v));
// 使用 Stream 过滤值大于 15 的项
Map<string integer> filtered = map.entrySet().stream()
.filter(e -> e.getValue() > 15)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}</string></string>
遍历时修改集合结构会引发什么异常
如果在增强型 for 循环中直接调用 map.remove() 或 map.put(),会立即触发 ConcurrentModificationException。这是因为增强循环内部使用了迭代器,而迭代器在创建时会记录 modCount,任何对 Map 结构的直接修改都会改变这个计数,导致迭代器检测到并发修改。要解决这个问题,必须使用迭代器自身的 remove() 方法,或者在 Java 8+ 中使用 removeIf 方法,它们能安全地处理结构变更。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











