java.util.ConcurrentModificationException 问题处理

java.util.ConcurrentModificationException 问题处理


 

在对Map集合进行处理时,有时需要对Map集合中的键值对进行过滤删除处理。

例如:对key值进行判断,不满足需求(key值不为“key1”)的需要进行过滤。

1、执行报错的代码如下:

public class TraverseMapTestDelete {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");

        for (String key : map.keySet()) {
            if ("key1".equals(key)) {
                map.remove(key);
            }
        }

        map.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

报错信息如下:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
    at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
    at com.miracle.luna.lambda.TraverseMapTestDelete.main(TraverseMapTestDelete.java:19)

2、正确代码如下(需要使用 Iterator 迭代器遍历Map):

/**
 * Created by Miracle Luna on 2020/3/17
 */
public class TraverseMapDelete {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");

        // 在遍历过程中,有删除某些Key-Value的需求,可以使用这种遍历方式)
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            if ("key1".equals(entry.getKey())) {
                iterator.remove();
            }
        }

        map.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

【注意!!!】此处必须用  iterator.remove();  进行在遍历的过程中删除键值对,

而不能用 map.remove(entry.getKey()); 或者  map.remove(entry.getKey(), entry.getValue());

执行结果如下:

key2 : value2
key3 : value3

参考博客https://www.cnblogs.com/hanmou/p/4156052.html

猜你喜欢

转载自www.cnblogs.com/miracle-luna/p/12508303.html