文章目录
- 一、报错ConcurrentModificationException问题
- 二、解决方式
- 方法 1: 使用 Iterator
- 2.flink
提示:以下是本篇文章正文内容,下面案例可供参考
一、报错ConcurrentModificationException问题
总共情况在Java hashmap和flink mapstate操作不当都会报这个错。报错原因:
这是因为 HashMap 不允许在迭代过程
中修改集合(移除已有的或新增)。
二、解决方式
方法 1: 使用 Iterator
使用 Iterator 遍历并移除元素。这是最安全的方法之一,因为它提供了 remove() 方法来移除当前元素。
// 创建一个示例 MapMap<String, Integer> exampleMap = new HashMap<>();exampleMap.put("key1", 10);exampleMap.put("key2", 20);exampleMap.put("key3", 30);exampleMap.put("key4", 40);Iterator<Map.Entry<String, Integer>> iterator = exampleMap.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<String, Integer> entry = iterator.next();if (entry.getValue() == 30) {iterator.remove(); // 移除符合条件的条目}}
2.flink
mapvalue也是上面类似的操作。通过遍历使用 iterator.remove();来移除数据。
如果想对mapvalue 在循环遍历时修改value值是可以的。
举例:将相同的key和修改完成的value再put到mapvalue中是可以的(前提是key相同时可以,如果key不同,则相当于mapstate新增数据会报错)