This article explores different ways to remove elements from a mutable list in Kotlin that satisfies the given predicate while iterating over it using a loop or an iterator.

It is not recommended adding or removing elements from a list within a loop as an index of its elements, and its length is changed. This is because it might lead to incorrect results due to skipped elements or java.util.IndexOutOfBoundsException or java.util.ConcurrentModificationException will be thrown to avoid non-deterministic behavior at a later stage.

Issues with removing elements from a list in Java/Kotlin within a loop

 
There are several workarounds to deal with this problem. These are discussed below:

1. Iterating Backwards

The suggested solution is to iterate backward in the list. This way, no elements will be skipped from the list.

Download Code

2. Decremeting index

Another trick is to iterate forward in the list and decrement the loop index whenever an element is removed.

Download Code

3. Using Iterator’s remove() function

To avoid java.util.ConcurrentModificationException being thrown, you can use iterator’s own remove() function.

Download Code

4. Using removeAll() function

Alternatively, you can create a separate collection of elements to be deleted and delete them later from the list using the removeAll() function.

Download Code

That’s all about removing elements from a list while iterating in Kotlin.