import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class HelloWorld{
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
IntStream.range(0, 20).forEach(i -> map.put(Integer.toString(i), i % 2 == 0 ? null : "ok"));
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() == null) {
map.remove(entry.getKey());
}
}
}
}
这是一个示例代码,我试图从给定的 HashMap 中删除空值。但这段代码给出了 ConcurrentModificationException。知道如何解决这个问题吗?
编辑:感谢 YCF_L,如果我用 map.entrySet().removeIf(entity -> entity.getValue() == null);
替换整个循环,上面的代码会有所帮助。
问题2:
如果 hashmap 是嵌套的怎么办?
- 情况 1 -> 如果值为 null,我想删除
- 情况 2 -> 如果该值是一个 hashmap,其嵌套哈希中的每个元素都为 null,则我想删除,如果其嵌套嵌套,则依此类推。
Ex 代码:
public static void removeEmptyValues(Map<String, Object> entityMap) {
for (Map.Entry<String, Object> entry : entityMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value == null) {
entityMap.remove(key);
} else if (value instanceof Map) {
removeEmptyValues((Map) value);
if (((Map) value).isEmpty()) {
entityMap.remove(key);
}
}
}
}
最佳答案
您可以使用 Collection::removeIf
解决此问题像这样:
map.entrySet().removeIf(entity -> entity.getValue() == null);
抛出此错误的原因是您同时迭代 Hashmap 的值,通过删除值来更改它,然后继续迭代。这就是引发异常的原因。
另请参阅此答案:
Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop
关于java - 从嵌套 HashMap 中删除条目时java中的ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176085/