首页 > 解决方案 > 如何使用 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);
                }
            }
        }
    }

标签: javaconcurrenthashmap

解决方案


推荐阅读