This article explores different ways to conditionally remove elements from a mutable list in Kotlin.

It is not permissible to modify a list while iterating over it; otherwise, ConcurrentModificationException will be thrown. However, you can use any of the following methods to safely remove elements from the list that doesn’t involve iterating it.

1. Using removeAll() function

The idea is to collect a list of elements that match the given predicate and then pass that collection to the removeAll() function. This will remove those elements from the original list.

Download Code

2. Using remove() function

Since you can’t modify a list while iterating over it, you can create a filtered list of elements to be removed and then remove those elements from the original list. This can be implemented as follows using filter() and forEach() function:

Download Code

3. Using removeIf() function

The simplest solution is to directly call the removeIf() function, which removes all elements from the list that satisfies the given predicate.

Download Code

That’s all about conditionally remove elements from a list in Kotlin.