Getting a ConcurrentModificationException thrown when removing an element from a java.util.List during list iteration? [duplicate]

Solution 1:

I believe this is the purpose behind the Iterator.remove() method, to be able to remove an element from the collection while iterating.

For example:

Iterator<String> iter = li.iterator();
while(iter.hasNext()){
    if(iter.next().equalsIgnoreCase("str3"))
        iter.remove();
}

Solution 2:

The Java 8 way to remove it from the List without Iterator is:

li.removeIf(<predicate>)

i.e.

List<String> li = new ArrayList<String>();
// ...
li.removeIf(st -> !st.equalsIgnoreCase("str3"));

Solution 3:

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception

Taken from http://download.oracle.com/javase/1.4.2/docs/api/java/util/ConcurrentModificationException.html

Solution 4:

yes people run into it -- the problem is you can't modify the list while iterating over it. I have used 2 alternatives in the past:

  1. You can keep track of the indexes of the items you want to remove, and then remove them after you are done iterating.
  2. Or you can copy all the ones you want to keep into a new list as you iterate, and then discard the old list when done.

those options assume you have to iterate over the list to find the elements to remove -- useful in cases where the list elements are complex objects with properties you might test on.

In your particular case, you dont even need to iterate, as you can just use removeAll. Look at the API here. There are also nifty methods like retainAll that discard everything that is not in the argument. You can use remove/retain-like methods whenever the objects in the list implement equals and hashcode properly. If you cannot rely on equals/hashcode to identify equality between instances in your app, you will have to do the removal yourself....