This article explores different ways to filter a list in-place with Kotlin.

1. Using Iterator’s remove() function

The simple approach to filtering a MutableList in-place is to iterate through the list using an iterator and remove the list elements using iterator’s remove() function.

Download Code

 
Please note that ConcurrentModificationException will be thrown if remove() function of MutableList is used instead.

2. Using retainAll() function

The recommended solution is to use the retainAll() function that only retains elements of MutableList that match with the given predicate.

Download Code

3. Using removeAll() function

Alternatively, you can use the removeAll() function that removes elements of MutableList that match with the given predicate.

Download Code

4. Using filter() function

If you don’t want to modify the original list or the given list is immutable, you can call the filter() function, which creates a new list containing all elements matching the given predicate.

Download Code

5. Using filterNot() function

Alternatively, you can use the filterNot() function, which returns a list containing all elements except the given predicate.

Download Code

That’s all about filtering a list in Kotlin.