How to remove element from Arraylist in java while iterating


In this tutorial, you will learn how to remove element from Arraylist in java while iterating using different implementations provided by Java.

It is necessary to understand the right way to remove items from a List because we might encounter errors in our programs if not done correctly.

For example, If we try to remove an item directly from a List while iterating through the List items, a ConcurrentModificationException is thrown.

The ConcurrentModificationException is an Exception that occurs when a thread tries to modify another thread that is iterating over the list items.

Since List is an Iterator implementation, the behavior of the iterator is undefined at this point, and if the iterator detects the behavior, it will throw the Exception.

To see this behavior in action, we will create an implementation that throws a ConcurrentModificationException and then implement different ways to solve the problem.

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.

Create a list of names and pass the list to the removeItems() method, and when you run the program, notice that it throws a ConcurrentModificationException.


Exception in thread “main” java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(
at java.base/java.util.ArrayList$
at com.java2code.RemoveListItems.removeItems(
at com.java2code.RemoveListItems.main(

Create a class named Customer with field firstName and lastName and generate allArgsConstructor, getter, setter, and toString() methods. We will use this class to create our custom list of objects and try to remove an object from a list based on a condition.

Using Collection’s removeIf() method

The removeIf() is a method from the Collection interface that accepts a Predicate which is simply a functional interface that accepts one value and returns a boolean.

This method removes all the elements that evaluate the Predicate to true, and any runtime exceptions that occur during the iteration are passed to the caller.

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 element.

If any elements are removed, the method returns true, and if the provided filter is null, it throws a NullPointerException.

Create a list of customer objects and use the equals() method in the removeIf() method to remove a specified name if found in the List.

Log the modified list to the console and observe that the customer with the given name was removed from the list.


Customer{firstName=’mary’, lastName=’public’}
Customer{firstName=’peter’, lastName=’parker’}
Customer{firstName=’alex’, lastName=’anderson’}

Using ListIterator class

ListIterator is an Iterator implementation that allows us to modify a list during the iteration and traversed in both forward and previous directions.

You can call next() or previous() when traversing the list, and the remove() method is implemented to operate on the last element returned by a call to previous or next.

If previous or next has not been called or you made a call to add or remove after the last call to previous or next, the method throws an IllegalStateException.

Create a list of integers and use the hasNext() method to iterate through the list and add an if statement that checks for an item using a call to next().

Remove the item from the list if it is found and log the modified list to the console to verify that the item was removed.



Using removeAll() method

The removeAll() is a method of the Collection interface that accepts a collection of elements and removes all the elements that are contained in the collection.

The method returns true if the collection changes as a result of the call.

The method throws UnsupportedOperationException if the method is not supported by this collection, a ClassCastException if the specified collection has a type incompatible with it, and a NullPointerException if the provided collection is null or has a null element or the specified collection, does not support null elements.

Create a list of elements and traverse through the list using the for-each method and add the elements you want to remove to a new List.

Call the modified list removeAll() method and pass the new list we have just created and observe that it removes the items in the new list from the original list.



Using Java 8 Stream to filter List items

Create a list of customer objects and call the stream() method from the list, which will return a Stream of the list items.

The Java 8 Stream will allow us to perform aggregate operations on the stream to get our desired output.

The stream() method will be followed by a call to the filter() method that accepts a Predicate which is a functional interface that accepts a single input and returns a boolean.

The filter method will remove the customer object that we specify and return a list with the remaining customer objects using the Collectors.toList() method.


Customer{firstName=’john’, lastName=’doe’}

Customer{firstName=’mary’, lastName=’public’}

Customer{firstName=’alex’, lastName=’anderson’}


In this tutorial, you have learned what is ConcurrentModificationException and how it comes about when removing items while traversing through a list. You have also learned how to avoid this Exception by using the removeIf(), removeAll(), ListIterator class, and Java 8 Stream.


You may also like:

Related Posts

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

  • Java ArrayList of objects
    25 January

    Create ArrayList of Objects in Java

    Table of ContentsUsing the add() method to create ArrayList of objects in javaUsing parameterized constructor to create ArrayList of objects in javaUsing addAll() method to create ArrayList of objects in javaConclusion In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and […]

  • Print HashMap in java
    30 June

    Print HashMap in Java

    Table of ContentsPrint from the HashMap ReferencePrint HashMap using foreach method with keyset()Print HashMap using Consumer with entrySet()Print HashMap using Arrays’s asList() methodPrint HashMap using Collections’s singletonList()Print HashMap using getkey() and getValue with entrySet()Print HashMap using BiConsumerPrint HashMap using IteratorPrint HashMap using custom ObjectsConclusion In this article, we will see how to print HashMap in […]

  • Print LinkedList in java
    26 June

    Print LinkedList in java

    Table of ContentsJava inbuilt LinkedListPrint LinkedList using a for loopPrint LinkedList using Enhanced for loopPrint LinkedList using streamsPrint LinkedList using toString() methodPrint LinkedList using IteratorPrint LinkedList using custom objectsCustom singly LinkedListHow to print a custom singly LinkedListConclusion Java inbuilt LinkedList Java inbuilt LinkedList class uses doubly linked list as internal data structure to store its […]

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • Print ArrayList in java
    11 May

    Print ArrayList in Java

    Learn about how to print ArrayList in java in different ways.

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.