Let me give a few examples with some alternatives to avoid a ConcurrentModificationException.

Suppose we have the following collection of books

List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));

Collect and Remove

The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.

ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
    if(book.getIsbn().equals(isbn)){
        found.add(book);
    }
}
books.removeAll(found);

This is supposing that the operation you want to do is "delete".

If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an addAll method at the end.

Using ListIterator

If you are working with lists, another technique consists in using a ListIterator which has support for removal and addition of items during the iteration itself.

ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
    if(iter.next().getIsbn().equals(isbn)){
        iter.remove();
    }
}

Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its add method to add new elements during iteration.

Using JDK >= 8

For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.

You could use the new removeIf method in the Collection base class:

ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));

Or use the new stream API:

ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
                           .filter(b -> b.getIsbn().equals(other))
                           .collect(Collectors.toList());

In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. books = filtered) or used the filtered collection to removeAll the found elements from the original collection (i.e. books.removeAll(filtered)).

Use Sublist or Subset

There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:

books.subList(0,5).clear();

Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.

Something similar could be achieved with sorted sets using NavigableSet.subSet method, or any of the slicing methods offered there.

Considerations:

What method you use might depend on what you are intending to do

  • The collect and removeAl technique works with any Collection (Collection, List, Set, etc).
  • The ListIterator technique obviously only works with lists, provided that their given ListIterator implementation offers support for add and remove operations.
  • The Iterator approach would work with any type of collection, but it only supports remove operations.
  • With the ListIterator/Iterator approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.
  • The JDK 8 streams example don't actually removed anything, but looked for the desired elements, and then we replaced the original collection reference with the new one, and let the old one be garbage collected. So, we iterate only once over the collection and that would be efficient.
  • In the collect and removeAll approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.
  • I think it is worth mentioning that the remove method of the Iterator interface is marked as "optional" in Javadocs, which means that there could be Iterator implementations that throw UnsupportedOperationException if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.
Answer from Edwin Dalorzo on Stack Overflow
Top answer
1 of 9
641

Let me give a few examples with some alternatives to avoid a ConcurrentModificationException.

Suppose we have the following collection of books

List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));

Collect and Remove

The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.

ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
    if(book.getIsbn().equals(isbn)){
        found.add(book);
    }
}
books.removeAll(found);

This is supposing that the operation you want to do is "delete".

If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an addAll method at the end.

Using ListIterator

If you are working with lists, another technique consists in using a ListIterator which has support for removal and addition of items during the iteration itself.

ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
    if(iter.next().getIsbn().equals(isbn)){
        iter.remove();
    }
}

Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its add method to add new elements during iteration.

Using JDK >= 8

For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.

You could use the new removeIf method in the Collection base class:

ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));

Or use the new stream API:

ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
                           .filter(b -> b.getIsbn().equals(other))
                           .collect(Collectors.toList());

In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. books = filtered) or used the filtered collection to removeAll the found elements from the original collection (i.e. books.removeAll(filtered)).

Use Sublist or Subset

There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:

books.subList(0,5).clear();

Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.

Something similar could be achieved with sorted sets using NavigableSet.subSet method, or any of the slicing methods offered there.

Considerations:

What method you use might depend on what you are intending to do

  • The collect and removeAl technique works with any Collection (Collection, List, Set, etc).
  • The ListIterator technique obviously only works with lists, provided that their given ListIterator implementation offers support for add and remove operations.
  • The Iterator approach would work with any type of collection, but it only supports remove operations.
  • With the ListIterator/Iterator approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.
  • The JDK 8 streams example don't actually removed anything, but looked for the desired elements, and then we replaced the original collection reference with the new one, and let the old one be garbage collected. So, we iterate only once over the collection and that would be efficient.
  • In the collect and removeAll approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.
  • I think it is worth mentioning that the remove method of the Iterator interface is marked as "optional" in Javadocs, which means that there could be Iterator implementations that throw UnsupportedOperationException if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.
2 of 9
51

Old Timer Favorite (it still works):

List<String> list;

for(int i = list.size() - 1; i >= 0; --i) 
{
        if(list.get(i).contains("bad"))
        {
                list.remove(i);
        }
}

Benefits:

  1. It only iterates over the list once
  2. No extra objects created, or other unneeded complexity
  3. No problems with trying to use the index of a removed item, because... well, think about it!
🌐
Mkyong
mkyong.com › home › java › java – how to remove items from a list while iterating?
Java – How to remove items from a List while iterating? | mkyong.com
May 12, 2021 - package com.mkyong.basic; import java.util.ArrayList; import java.util.List; public class IteratorApp2B { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); // remove if item is 1 or 3 list.removeIf(x -> x == 1 || x == 3); System.out.println(list); } } ... Review the Java 8 Collection#removeIf method signature, and the API uses Iterator to remove the item while iterating it.
Discussions

java - Removing elements on a List while iterating through it - Code Review Stack Exchange
I needed a way to remove elements on a List while iterating through it. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 27, 2014
java - Removing Object from a list during for loop - Stack Overflow
I am trying to remove an object with a certain attribute from a list of Objects, I have red other questions about this problem but I guess I am missing something. this method doesn't work, becau... More on stackoverflow.com
🌐 stackoverflow.com
Java - removing an element in list while iterating it with a for index loop - Stack Overflow
I know that removing an element from a list while iterating it is not recommended. You better use iterator.remove(), java streams, or copy the remove to an external list. But this simple code just... More on stackoverflow.com
🌐 stackoverflow.com
java - Removing item from list while iterating - Stack Overflow
1 Removing an element of a Collection inside a thread inside the iterator · 1 Remove item from list while using iterator without acess to iterator Java More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/processing › question and solution: how to delete or add an object to/from array list while iterating it.
r/processing on Reddit: Question and solution: How to delete or add an object to/from array list while iterating it.
December 28, 2022 - By iterating with a classic for loop from backwards, adding or removing an object to/from the end of the list wont effect the loop. So it should be: ... I was talking with u/AgardenerCoding about the problem.
🌐
Java67
java67.com › 2018 › 12 › how-to-remove-objects-or-elements-while-iterating-Arraylist-java.html
How to Remove Objects From ArrayList while Iterating in Java - Example Tutorial | Java67
You can avoid that by using Iterator's remove() method, which removes the current object in the iteration. Other ArrayList tutorials for Java Programmers · How to remove duplicate elements from ArrayList in Java?
Top answer
1 of 5
80

There are several ways to do this. Let's look at the alternatives:

Iterating over a copy, removing from original

This is a simple solution for the underlying problem of your first code: A ConcurrentModificationException is thrown because you iterate through the list and removing from it at the same time.

Easy solution is to create a copy of the list and iterate through that.

for (Integer integer : new ArrayList<>(nums)) {
    if (integer < 3) {
        nums.remove(integer);
    }
}

Down-sides of this approach:

  • Creates a copy of the original list, which requires memory and an operation which performance depends on the type of the list (ArrayList, LinkedList, etc.)
  • Additionally, nums.remove(value) is a \ operation. Making this loop overall \

Java 8 Streams

List<Integer> filteredList = nums.stream().filter(i -> i >= 3).collect(Collectors.toList());

Down-sides:

  • Does not actually modify the existing list, so if references to the list are spread around various variables, you still have some old elements that just shouldn't be in that list.
  • Creates various stream-related objects which might not be the most effective option.

On the up-side, this is among the fastest for bigger lists.

If you're not using Java 8:

List<Object> originalList;
List<Object> newList = new YourFavoriteListType<>();
for (Object obj : originalList) {
    if (shouldKeep(obj)) {
        newList.add(obj);
    }
}

Java 8 method

nums.removeIf(i -> i < 3);

Java 8 introduced the default method removeIf on the Collection interface. This allows different implementations to have implementation-specific performance-optimized implementations of this method.

Iterator.remove()

Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
    Integer integer = it.next();
    if (integer < 3) {
        it.remove();
    }
}

The only down-side of this approach is that you need to switch your for-each to a while. However, this approach is the most efficient one, especially for LinkedList where it is \ (it's \ for ArrayList because it has to copy array data on each remove(index) call). This is the approach I would recommend in most cases.

Note: Instead of using a while-loop it can also be written as:

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer integer = it.next();
    ...

Conclusion

If you want to mutate the existing list, removeIf is the solution I would go with. If you like functional programming and prefer a new list instead of mutating the existing one, then go with the list.stream().filter(...).collect(Collectors.toList()) approach.

See also

"When to use LinkedList over ArrayList?" on Stack Overflow

2 of 5
22

Just had to do something very similar (hence why I'm here), ended up using Java8's Collection.removeIf(Predicate<? super E> filter)

With your code it would look like:

nums.removeIf((Integer i)->{return i<3;});

And if you wanted to collect the removes:

List<Integer> removed = new ArrayList<>();
nums.removeIf(
    (Integer i)->{
        boolean remove = i<3;
        if (remove) {
            removed.add(i);
        }
        return remove;
    });
🌐
Cscode
cscode.io › java › collections › delete list element while iterating
How to delete elements while iterating from List in Java | CsCode.io
public void deleteWhileIteratingListUsingIterator() { List<String> arrayList = new ArrayList<>(List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")); System.out.println("BEFORE - arrayList size : "+ arrayList.size() + " , elements ...
🌐
Coderanch
coderanch.com › t › 521642 › java › remove-element-list-iterating
remove the element in list while iterating through it. (Java in General forum at Coderanch)
Bharath Raja wrote:this works fine, and achieve my requirement exactly.. thanks folks... You are welcome ... When you remove elements from a list that you are iterating over, then the iterator will get confused and it will throw a ConcurrentModificationException when you get the next element.
Find elsewhere
🌐
Java2Blog
java2blog.com › home › core java › java collections › how to remove element from arraylist in java while iterating
How to remove element from Arraylist in java while iterating - Java2Blog
September 10, 2021 - The items in the list are traversed using iterator(), and any matching item is removed using the remove() method. If the iterator implementation does not support remove operation, it throws UnsurpportedOperationException on the first matching ...
🌐
Codecademy
codecademy.com › docs › java › iterator › .remove()
Java | Iterator | .remove() | Codecademy
June 30, 2022 - The .remove() method removes an item from the underlying collection of an Iterator or a ListIterator object. This method removes the current element (i.e., the one returned by the last .next() or .previous() method).
🌐
Techie Delight
techiedelight.com › home › java › remove elements from a list while iterating over it in java
Remove elements from a list while iterating over it in Java | Techie Delight
July 7, 2026 - Issues with removing elements from a list in Java/Kotlin within a loop · There are several workarounds to deal with this problem. These are discussed below: We have seen that moving forward in the list using a for-loop and removing elements from it might cause us to skip a few elements. One workaround is to iterate backward in the list, which does not skip anything.
🌐
Coderanch
coderanch.com › t › 741104 › java › iterator-remove-remove-element-collection
Why I must use iterator.remove() to remove element from my collection? (Beginning Java forum at Coderanch)
That is how Iterators are designed. While the iterator is in operation, it insists on being the only thing to alter the structure of your Collection. You can remove elements with the other methods of the Collection interface, but only when there aren't any Iterators around.
🌐
Baeldung
baeldung.com › home › java › java list › removing an element from an arraylist
Removing an Element From an ArrayList | Baeldung
April 4, 2025 - Therefore, if we’re using JDK 21 or higher, this method can be a good option for removing the last element from a List. Sometimes, we want to remove an element from an ArrayList while we’re looping it. Due to not generating a ConcurrentModificationException, we need to use the Iterator class to do it properly.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-remove-an-element-from-arraylist-using-listiterator
Java Program to Remove an Element from ArrayList using ListIterator - GeeksforGeeks
July 23, 2025 - Increment the iterator by listIterator.next() and move to element which you want to remove; Remove the element by listIterator.remove(); Print the list after removing the element.
🌐
Quora
quora.com › How-do-I-remove-items-from-a-list-while-iterating
How to remove items from a list while iterating - Quora
Answer (1 of 9): There are many ways in which you can do that. for item in list: list.remove(item) This won’t work because in one for loop it will only delete the alternate items present in the list. So you have to use the conventional way or you can use n/2 number of for loops which will make...
🌐
Quora
quora.com › How-will-you-efficiently-remove-elements-while-iterating-a-Collection
How will you efficiently remove elements while iterating a Collection? - Quora
Answer (1 of 2): The right way to remove elements from a collection while iterating is by using ListIterator.remove() method. E.g. [code]ListIterator iter = myList.iterator(); while(iter.hasNext()) { itr.remove(); } [/code]Some developers use following code to remove an element which...
🌐
Benchresources
benchresources.net › home › java › java – how to add/remove/modify an element in list while iterating ?
Java - How to add/remove/modify an element in List while iterating ? - BenchResources.Net
July 20, 2022 - We will see 2 different examples using Iterator and ListIterator, ... But there should be some operations involving obtained iterator otherwise program throws java.lang.IllegalStateException · Note:- use remove() method of Iterator interface for removing elements from iterating List otherwise ...
🌐
Stack Overflow
stackoverflow.com › questions › 54448641
java - Removing Object from a list during for loop - Stack Overflow
Class java.util.Iterator has a remove() method to allow you to remove an item from a list while iterating through the list. The below URL has examples and more explanation. https://www.geeksforgeeks.org/remove-element-arraylist-java/
🌐
Stack Overflow
stackoverflow.com › questions › 25613927 › removing-item-from-list-while-iterating
java - Removing item from list while iterating - Stack Overflow
While iterating through a list, an item can possibly be removed. private void removeMethod(Object remObj){ Iterator it = list.iterator(); while (it.hasNext()) { Object cur...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-remove-an-element-from-collection-using-iterator-object-in-java
How to Remove an Element from Collection using Iterator Object in Java? - GeeksforGeeks
July 23, 2025 - An if condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method. When the entire list is traversed again the element which was removed is no longer present in the list.