Can we remove object from list while iterating in Java?

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

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 void filterList[List list, Predicate 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 colors = new ArrayList[Arrays.asList["BLUE", "RED", "RED", "YELLOW"]];
filterList[colors, i -> i.equals["RED"]];
System.out.println[colors]; // [BLUE, YELLOW]
}
}

DownloadRun Code

“java remove elements from list while iterating” Code Answer


java remove from arraylist while iterating
java by Inquisitive Ibex on Jul 24 2020 Comment
4
Source: stackoverflow.com
Add a Grepper Answer

Java answers related to “java remove elements from list while iterating”


Java queries related to “java remove elements from list while iterating”

“remove items from arraylist while iterating java” Code Answer


java remove from arraylist while iterating
java by Inquisitive Ibex on Jul 24 2020 Comment
4
Source: stackoverflow.com
Add a Grepper Answer

Java answers related to “remove items from arraylist while iterating java”


Java queries related to “remove items from arraylist while iterating java”

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.

Video liên quan

Bài mới nhất

Chủ Đề