0

I have a HashMap:

public static Map<String, Set<String>> adjMap = new HashMap<String, Set<String>>();
adjMap.put(title, new HashSet<String>());
adjMap.get(title).add(cutTitle(graphLink));

Now I want do delete all entries from the values (HashSet), which does not contains as a key.

Here is my code so far:

for(String s: adjMap.keySet()){
    for(Set<String> s1: adjMap.values()){
        for(String s2: s1){
            if(!s.contains(s2)){
                s1.remove(s2);
            }
        }
    }
}

But I get an exception:

Exception in thread "main" java.util.ConcurrentModificationException

moses
  • 155
  • 3
  • 15

3 Answers3

2

Iterate your Map

Iterator it = adjMap.entrySet().iterator();
    while (it.hasNext())
    {
       Entry item = it.next();
       map.remove(item.getKey());
    }
Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
0

I think for-each loops are not allowed to alter the iterated object. To remove entries you should use an iterator.

Compare to map-Iteration for an example.

Community
  • 1
  • 1
Jannek S.
  • 365
  • 3
  • 16
0

You can use ConcurrentHashMap instead, or create a copy of your HashMap and make any changes to the copy.

D. Krauchanka
  • 264
  • 3
  • 15