0

I've been stuck on this for awhile now. I am trying to remove elements of a set if they make a set criteria. However when iterating when I try to remove the element it fails.

I get the java.util.ConcurrentModificationException

private static void smallerSet(Set<Map<String, Int>> set){

    for (Map<String, Integer> map : set){

        for (String String : map.keySet()){

            if ( true){
                set.remove(map);

            }
            else{
                //System.out.println("test");


            }

        }
    }
}

Any advice would be greatly appreciated.

1 Answers1

1

You cannot remove elements from a Collection while iterating over it with the enhanced for loop.

You should use an explicit Iterator and remove with the Iterator's remove() method:

Iterator<Map<String, Integer>> iter = set.iterator();
while (iter.hasNext ()) {
    Map<String, Integer> map = iter.next();
    for (String str : map.keySet()){
        if (some condition) {
            iter.remove();
            break; // you should probably break from the inner loop
                   // after removing an element
        } else {
            //System.out.println("test");
        }
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768