This article explores different ways to remove null values from a list in Kotlin.

1. Using removeIf() function

The removeIf() function removes all elements of the list that satisfy the given predicate. To remove null values from the list, you can use a lambda expression to find null values.

Download Code

2. Using removeAll() function

To remove all occurrences of null values from a list, you can pass a singleton list having only a null value to the removeAll() function.

Download Code

3. Using filter() function

You can use the filter() function that returns a new list consisting of the elements matching the specified predicate. You can specify a lambda expression to return a new list with null values removed from the list, as shown below:

Download Code

4. Using filterNotNull() function

A simple and fairly efficient solution is to remove null values from a list to call the filterNotNull() function on the list. Note, this approach creates a new list.

Download Code

5. Using remove() function

The remove() function removes the first occurrence of the specified object from the list. To remove all null occurrences from the list, you can continuously call remove(null) until all null values are removed from the list.

Download Code

6. Using List Iterator

Alternatively, you can loop over the list using an iterator and remove all null elements from it.

Download Code

7. Map the null values

Instead of removing null values from a list, you can also replace the null values with some value. This approach is demonstrated below:

Download Code

That’s all about removing null values from a list in Kotlin.