How do you remove an element from an ArrayList while iterating?

Java – How to remove items from a List while iterating?

By | Last updated: May 12, 2021

Viewed: 14,231 (+351 pv/w)

Tags:iterator | java 8 | java collections | list | loop list | predicate

In Java, if we remove items from a List while iterating it, it will throw java.util.ConcurrentModificationException. This article shows a few ways to solve it.

Table of contents

  • 1. java.util.ConcurrentModificationException
  • 2. Java 8 Collection#removeIf
    • 2.1 removeIf examples
    • 2.2 removeIf uses Iterator
  • 3. ListIterator example
  • 4. Filter and Collect example
  • 5. References

P.S Tested with Java 11.

1. Iterating backwards

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Main
{
// Generic method to remove elements from a list in Java
public static <T> void filterList(List<T> list, Predicate<T> condition)
{
for (int i = list.size() - 1; i >= 0 ; i--)
{
if (condition.test(list.get(i))) {
list.remove(i);
}
}
}
public static void main(String[] args)
{
List<String> colors = new ArrayList<>(Arrays.asList("BLUE", "RED", "RED", "YELLOW"));
filterList(colors, i -> i.equals("RED"));
System.out.println(colors); // [BLUE, YELLOW]
}
}

DownloadRun Code

Introduction

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.

1. Overview

In this tutorial, we're going to see how to remove elements from an ArrayList in Java using different techniques. Given a list of sports, let's see how we can get rid of some elements of the following list:

List<String> sports = new ArrayList<>(); sports.add("Football"); sports.add("Basketball"); sports.add("Baseball"); sports.add("Boxing"); sports.add("Cycling");

How to remove an element from ArrayList in Java?

ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions, newer methods are being available as if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it been introduced in java version8, so do we have more ways to operate over Arraylist to perform operations. Here we will be discussing a way to remove an element from an ArrayList.

While removing elements from ArrayList there can either we are operating to remove elements over indexes or via values been there in an ArrayList. We will be discussing both ways via interpreting through a clean java program.

Methods:

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows:

  1. Using remove() method by indexes(default)
  2. Using remove() method by values
  3. Using remove() method over iterators

Note: It is not recommended to use ArrayList.remove() when iterating over elements.



Method 1: Using remove() method by indexes

It is a default method as soon as we do use any method over data structure it is basically operating over indexes only so whenever we do use remove() method we are basically removing elements from indices from an ArrayList.

ArrayList class provides two overloaded remove() methods.

  • remove(int index): Accept index of the object to be removed
  • remove(Object obj): Accept object to be removed

Let us figure out with the help of examples been provided below as follows:

Example:




// Java program to Remove Elements from ArrayList
// Using remove() method by indices
// Importing required classes
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List interface with
// reference to ArrayList class
List<Integer> al = new ArrayList<>();
// Adding elements to our ArrayList
// using add() method
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// Printing the current ArrayList
System.out.println(al);
// This makes a call to remove(int) and
// removes element 20
al.remove(1);
// Now element 30 is moved one position back
// So element 30 is removed this time
al.remove(1);
// Printing the updated ArrayList
System.out.println(al);
}
}
Output [10, 20, 30, 1, 2] [10, 1, 2]

Now we have seen removing elements in an ArrayList via indexes above, now let us see that the passed parameter is considered an index. How to remove elements by value.

Method 2: Using remove() method by values

Example:




// Java program to Remove Elements from ArrayList
// Using remove() method by values
// Importing required classes
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List interface with
// reference to ArrayList
List<Integer> al = new ArrayList<>();
// Adding elements to ArrayList class
// using add() method
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// Printing the current ArrayList
System.out.println(al);
// This makes a call to remove(Object) and
// removes element 1
al.remove(new Integer(1));
// This makes a call to remove(Object) and
// removes element 2
al.remove(new Integer(2));
// Printing the modified ArrayList
System.out.println(al);
}
}

Output :

[10, 20, 30,1 ,2] [10, 20, 30]

Note: It is not recommended to use ArrayList.remove() when iterating over elements.

Method 3: Using Iterator.remove() method

This may lead to ConcurrentModificationException When iterating over elements, it is recommended to use Iterator.remove() method.

Example:




// Java program to demonstrate working of
// Iterator.remove() on an integer arraylist
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList
List<Integer> al = new ArrayList<>();
// Adding elements to our ArrayList
// using add() method
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// Printing the current ArrayList
System.out.println(al);
// Creating iterator object
Iterator itr = al.iterator();
// Holds true till there is single element
// remaining in the object
while (itr.hasNext()) {
// Remove elements smaller than 10 using
// Iterator.remove()
int x = (Integer)itr.next();
if (x < 10)
itr.remove();
}
// Printing the updated ArrayList
System.out.print(al);
}
}
Output [10, 20, 30, 1, 2] [10, 20, 30]

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

How do you remove an element from an ArrayList while iterating?




Article Tags :
Java
Java-ArrayList
Java-Collections
java-list
Java-List-Programs
Practice Tags :
Java
Java-Collections