How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

Ernestas Gruodis picture Ernestas Gruodis · Aug 26, 2013 · Viewed 414k times · Source

I'm trying to remove some elements from an ArrayList while iterating it like this:

for (String str : myArrayList) {
    if (someCondition) {
        myArrayList.remove(str);
    }
}

Of course, I get a ConcurrentModificationException when trying to remove items from the list at the same time when iterating myArrayList. Is there some simple solution to solve this problem?

Answer

arshajii picture arshajii · Aug 26, 2013

Use an Iterator and call remove():

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}