java - 如何使用 HashSet 迭代 ConcurrentHashMap作为值并在遍历地图时从 HashSet 中删除一个字符串?
问题描述
我开始学习java并通过以下问题
在迭代时尝试更新 ConcurrentHashMap 的值(哈希集) - 调试时显示 ConcurrentModificationError - 尽管代码没有崩溃
这是场景:
concurrentMap =
Key -> A
Value -> ["a","b","c","d"]
Key -> B
value -> ["a", "j", "k", "l", "m"]
当我在迭代 A 时尝试删除“a”时,它无法正确更新哈希集并且无法循环我看到哈希集更新如下
[a, b, c, d]
[b,c]
如何在迭代 A 并正确更新 hashSet 时从键 A 中删除“a”?
private ConcurrentMap<String, HashSet<String>> concurrentMap = new ConcurrentHashMap<>();
private void parseItems(Item testItem) throws Exception {
Map<String, HashSet<String>> itemMap = ConcurrentHashMap <>(Myclass.getIdMap(testItem));
concurrentMap = new ConcurrentHashMap<>(itemMap);
for (String type : concurrentMap.keySet()) {
for (String id : concurrentMap.get(type)) {
if (type.equals("MyType")) {
myList = function1(MyType, id);
} else {
myList = function2(defaultType, id, "ID");
}
removeParsedIdFromCurrentMap(type, id);
for (Item item : myList) {
ConcurrentMap<String, HashSet<String>> newItemConcurrentMap = new ConcurrentHashMap<>(Myclass.getIdMap(item));
addToConcurentMap(newItemConcurrentMap);
}
}
}
}
private void removeParsedIdFromCurrentMap(String type, String id) {
HashSet<String> currentIdSet = concurrentMap.get(type);
//This removes the value 'a'
if (currentIdSet != null) {
Iterator<String> iter = currentIdSet.iterator();
while (iter.hasNext()) {
String toRemoveId = iter.next();
if (toRemoveId.contains(id)) {
iter.remove();
}
}
//How can I update the values of key A while iterating A?
updateConcurrentMap();
}
}
private void addToConcurentMap(ConcurrentMap<IOMType, HashSet<String>> newItemConcurrentMap ) {
for (String type : newItemConcurrentMap .keySet()) {
for (String id : newItemConcurrentMap .get(type)) {
if (!checkIdParsed(type, id)) {
concurrentMap.putIfAbsent(type, new HashSet<>());
concurrentMap.get(type).add(id);
}
}
}
}
解决方案
推荐阅读
- ios - Swift Firebase Storage 获取特定子项的所有下载 URL
- python - 如何使用 Python 正则表达式将点替换为空行或空行
- php - 如何使用 PHP 在单个表中显示来自两个不同 MYSQL 表的数据
- bash - Bash:从刚刚被捕获的错误中获取消息
- c# - 单元测试服务中如何模拟存储库方法
- azure - 使用 ManagedServiceIdentity 从逻辑应用程序到 Azure 函数时出现 301 永久重定向
- javascript - JavaScript 购物车无法正常运行
- c++ - 无法从派生类对象访问父类函数
- c# - 根据该键的属性确定字典是否包含键?
- java - 运算符 <= 不能应用于“E”、“E”、泛型类