【问题标题】:ConcurrentModificationException in java while deleting entries from nested hashmap [duplicate]从嵌套哈希图中删除条目时Java中的ConcurrentModificationException [重复]
【发布时间】:2018-10-15 00:14:01
【问题描述】:
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 -&gt; entity.getValue() == null); 替换整个循环,上面的代码会有所帮助

问题2:

如果 hashmap 是嵌套的呢?

  • 案例 1 -> 如果值为 null,我想删除
  • 案例 2 -> 如果值是一个哈希映射,其嵌套哈希中的每个元素都为空,我想删除它,如果嵌套嵌套,则依此类推。

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);
            }
        }
    }
}

【问题讨论】:

  • 迭代时不要删除/添加
  • 顺便说一句,你想达到什么目的?
  • @Andrew - 我想删除哈希图的所有空值。在上面的示例中,我明确创建了一个要删除的示例。在我的项目中,我将得到一个带有空值的哈希。我必须从中清除所有空值。
  • map.values().removeIf(Objects::isNull);

标签: java exception-handling java-8 java-stream concurrenthashmap


【解决方案1】:

您可以像这样使用Collection::removeIf 解决这个问题:

map.entrySet().removeIf(entity -> entity.getValue() == null);

引发此错误的原因是您同时迭代 Hashmap 的值,通过删除一个值来更改它,然后继续迭代。这就是引发异常的原因。

另请参阅此答案:

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

【讨论】:

  • 是的。这个补丁我也遇到了同样的错误。
  • 需要用YCF_L提供的代码替换整个迭代循环
  • @Sk.Irfan 这不可能我得到{11=ok, 13=ok, 15=ok, 17=ok, 19=ok, 1=ok, 3=ok, 5=ok, 7=ok, 9=ok} 并注意你必须用我的代码替换所有这些for (Map.Entry&lt;String, String&gt; entry : map.entrySet()) { if (entry.getValue() == null) { map.remove(entry.getKey()); } } 作为@SpyrosK 提及
  • @YCF_L - 同意,但是如果它的嵌套散列可以做什么?
  • 嵌套哈希是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
相关资源
最近更新 更多