0

I'm trying to iterate through a map and remove certain elements to construct a controlled vocabulary. Here is my code:

    public static Map<String, Integer> controlVocab(Map<String, Integer> docf){
    Set<String> set = docf.keySet();
    Iterator<String> itr = set.iterator();
    for (Map.Entry <String, Integer> entry : docf.entrySet())
    {
        if(entry.getValue()<50){
            docf.remove(entry.getKey());
        }
    }
    return docf;
}

But I keep getting this error: Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429) at java.util.HashMap$EntryIterator.next(HashMap.java:1463) at java.util.HashMap$EntryIterator.next(HashMap.java:1461) at org.tartarus.snowball.TestApp.controlVocab(TestApp.java:114) at org.tartarus.snowball.TestApp.main(TestApp.java:619)

Does this make sense?

wintvelt
  • 13,855
  • 3
  • 38
  • 43
kevin
  • 181
  • 1
  • 1
  • 5

1 Answers1

0

Yes this makes sense: as the official oracle documentation says is not generally permissible for one thread to modify a Collection while another thread is iterating over it.

Maybe a best way is to collect the element that you want delete in a new List and then iterating on this list remove the correspondent entry in the original Map.

Try something like that:

List<String> mylist = new ArrayList<String>();
for (Map.Entry <String, Integer> entry : docf.entrySet()){
        if(entry.getValue()<50){
            mylist.add(entry.getKey());
        }
}

for (String key : mylist){
        docf.remove(key);
}
Luca Pelosi
  • 131
  • 1
  • 4