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!
🌐
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?
🌐
Baeldung
baeldung.com › home › java › java list › removing an element from an arraylist
Removing an Element From an ArrayList | Baeldung
April 4, 2025 - 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.
🌐
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 -

Hi few days ago i was encountered a problem. While iterating an array list by a for each loop, i was trying to remove the current object in spesific conditional. Like:

Arraylist<someclass> mylist;

...

for (someclass element: mylist)

if element.data!=0; mylist.remove(element)

when i run the code it throws ConcurrentModificationException .

I think it is because of the size of arraylist changes and the next iteration also changes and it throws out error.

Then I remembered the solition from a book.

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:

for (int i=mylist.size()-1;i>=0;i--)

someclass element=mylist.get(i);

if element.data!=0; mylist.remove(i)

with this method it works and there was no error.

I was talking with u/AgardenerCoding about the problem. And he encouraged me to post this as it may be very useful for someone else searching for an answer to same problem.

🌐
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.Arrays; import java.util.List; public class IteratorApp1 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); for (String s : list) { if ("A".equals(s)) { // throws java.util.ConcurrentModificationException list.remove(s); } } System.out.println(list); } }
🌐
W3Schools
w3schools.com › java › ref_arraylist_remove.asp
Java ArrayList remove() Method
If a value is specified and multiple elements in the list have the same value then only the first one is deleted. If the list contains integers and you want to delete an integer based on its value you will need to pass an Integer object. See More Examples below for an example. ... T refers to the data type of items in the list. Remove an integer from the list by position and by value: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(8); list.add(9); list.add(1); list.remove(Integer.valueOf(1)); // Remove by object list.remove(1); // Remove by index System.out.println(list); } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-element-arraylist-java
How to remove an element from ArrayList in Java? - GeeksforGeeks
July 23, 2025 - Note: It is not recommended to use ArrayList.remove() when iterating over elements. Also new Integer( int_value) has been deprecated since Java 9, so it is better idea to use Integer.valueOf(int_value) to convert a primitive integer to Integer Object.
🌐
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)
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook ... Seetharaman Venkatasamy wrote:I would suggest you to use Iterator. For an example: this works fine, and achieve my requirement exactly.. thanks folks... Life is either daring something or nothing - Helen Keller ... 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
🌐
Crunchify
crunchify.com › java j2ee tutorials › in java how to remove elements while iterating a list, arraylist? (5 different ways)
In Java How to remove Elements while Iterating a List, ArrayList? (5 different ways) • Crunchify
November 8, 2021 - package crunchify.com.java.tutorials; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.stream.Collectors; /** * @author Crunchify.com * In Java How to remove Elements while Iterating a List? (5 different ways to remove items) */ public class CrunchifyRemoveItemFromList { public static void main(String[] args) { collectionRemoveIfMethod(); collectionRemoveIfObjectEqualsMethod(); collectionteratorRemoveMethod(); listIteratorWayToRemoveElement(); streamFilterCollectWay(); } // Method-1: collectionRemoveIfMethod to remove
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 \$O(n)\$ operation. Making this loop overall \$O(n^2)\$

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 \$O(n)\$ (it's \$O(n^2)\$ 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
Remove list elements using Iterator while iterating through List ... public void deleteWhileIteratingListUsingIterator() { List<String> arrayList = new ArrayList<>(List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")); System.out....
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-list-remove-methods-arraylist-remove
How To Use remove() Methods for Java List and ArrayList | DigitalOcean
September 9, 2025 - Turns the article into an evidence-based guide rather than generic rules of thumb. The remove(int) method removes the element at the specified index, while the remove(Object) method removes the first occurrence of the specified element. Here’s an example: List<String> list = new ArrayList<>(); ...
🌐
Blogger
javarevisited.blogspot.com › 2023 › 01 › how-to-remove-objects-from-arraylist.html
How to remove objects from ArrayList using Iterator in Java? Example Tutorial
Instead, use Iterator's remove() method for removing objects while iterating. You should also use Iterator, because that's the only option to modify collection during iteration, all other options e.g. enhanced for loop are read only way to traverse ...
🌐
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 - Create a method named removeItems() that accepts a list of names and inside it add a for-each loop that iterates through the list of names to find a name, and if it is found, we use the remove() method to remove it from the list.
🌐
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 - Iterator/traverse over the ArrayList and increment the list Iterator. If we reached the required element then break the loop else we reach the end and nothing will be deleted. ... // Java Program to Remove an element from ArrayList // using ...
🌐
YouTube
youtube.com › ram n java
How to remove elements from the ArrayList using Iterator? | Java Collection Framework - YouTube
Welcome to our Java Collection Framework tutorial! In this video, we will explore how to remove elements from an ArrayList using an Iterator in Java.### Over...
Published   October 10, 2014
Views   3K
🌐
TutorialsPoint
tutorialspoint.com › use-iterator-to-remove-an-element-from-a-collection-in-java
Use Iterator to remove an element from a Collection in Java
import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } Iterator i = aList.iterator(); String str = ""; while (i.hasNext()) { str = (String) i.next(); if (str.equals("Orange")) { i.remove(); System.out.println("\nThe element Orange is removed"); break; } } System.out.println("\nThe ArrayList elements are: "); for (String s: aList) { System.out.println(s); } } } The output of the above program is as follows ·
🌐
Codecademy
codecademy.com › docs › java › iterator › .remove()
Java | Iterator | .remove() | Codecademy
June 30, 2022 - Beginner Friendly.Beginner Friendly17 hours17 hours ... Where iterator is an Iterator or ListIterator object. This example populates an ArrayList and then removes the even items with the .remove() method: