删除Map中null键可直接用map.remove(null),删除null值需用Iterator或Java 8的entrySet().removeIf(entry -> entry.getValue() == null),避免ConcurrentModificationException。

在Java中,Map不允许键或值为null的情况需要特别处理,尤其是当你想删除空键(null键)或空值(null值)时。可以通过遍历Entry集合的方式安全地移除这些条目。
删除Map中的空键
Map中最多只能有一个键为null的条目。要删除这个空键条目,可以直接调用remove方法:
- map.remove(null):直接移除键为null的条目,无论其值是什么。
示例代码:
Mapmap = new HashMap<>(); map.put("a", "apple"); map.put(null, "banana"); map.put("c", "cherry"); // 删除空键 map.remove(null);
删除Map中的空值
如果要删除所有值为null的条目,不能在遍历时直接使用forEach或普通for循环调用remove,否则会抛出ConcurrentModificationException。正确做法是使用Iterator遍历并删除。
立即学习“Java免费学习笔记(深入)”;
- 通过entrySet().iterator()获取迭代器。
- 逐个判断value是否为null,是则调用iterator.remove()。
示例代码:
Mapmap = new HashMap<>(); map.put("a", "apple"); map.put("b", null); map.put("c", "cherry"); map.put("d", null); // 删除值为null的条目 Iterator > iterator = map.entrySet().iterator(); while (iterator.hasNext()) { if (iterator.next().getValue() == null) { iterator.remove(); } }
使用Java 8的简洁写法
可以利用replaceAll或结合removeIf简化操作。虽然Map本身没有removeIf,但其视图支持:
- 用entrySet().removeIf()一步删除满足条件的条目。
示例:
// 删除所有值为null的条目(Java 8+) map.entrySet().removeIf(entry -> entry.getValue() == null); // 删除键为null的条目(也可用) map.entrySet().removeIf(entry -> entry.getKey() == null);
这种方式更简洁且线程安全在单线程下没问题。
基本上就这些。根据你的JDK版本选择合适的方法,优先推荐Java 8的removeIf方式,干净利落。注意不要在增强for循环里直接删除元素,避免异常。










