This post will discuss the issues involved in removing elements from a list within a loop in Java and Kotlin.

It is tricky to add or remove elements from a list, within a loop, as the index of its elements and the length of the list is changed.

1. Incorrect output / IndexOutOfBoundsException

Consider the following example where we’re creating a list of colors and calling the filterList() method that is supposed to remove elements from the specified list that has a RED color.

Java


Download  Run Code

Kotlin



 
There are two RED color instances in the original list. Still, the Java code will only remove the first instance of RED, and the Kotlin code will throw java.lang.IndexOutOfBoundsException.

The second RED is skipped because it is adjacent to the first RED. Once the first RED is removed, the list order is changed, and the second RED takes the place of the first RED, but the index of the list also gets incremented by 1, which now points to BLUE color.

In other words, when the i'th element of the list is removed, the element positioned at the next index becomes the new i'th element. Now in the next iteration of the for-loop, since index i gets incremented, the unprocessed i'th element will be skipped.

2. Using java.util.ConcurrentModificationException

It is not permissible to modify a list while iterating over it; otherwise, java.util.ConcurrentModificationException will be thrown to avoid non-deterministic behavior at a later stage.

For example, consider the following example which throws a java.util.ConcurrentModificationException as they permit concurrent modification:

Java


Download  Run Code

Kotlin



 
Another plausible way of iteration is using the for-each loop (which internally uses an iterator):

Java


Download  Run Code

Kotlin



 
However, there are several workarounds to deal with this problem. These alternatives are discussed in detail in the following post:

Remove elements from a list while iterating over it in Java

That’s all about issues associated with removing elements from a list in Java or Kotlin within a loop.