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