Kotlin – Filter not null values in List

Kotlin – Filter not null values in a List

To filter not null values in a list in Kotlin, you can use List.filterNotNull() function.

The following is a step by step process to filter values that are not null in a List in Kotlin.

  1. Consider that we are given a list of values in mixedList. This list can contain values of any type including null values.
  2. Call filterNotNull() function on the mixedList.
  3. The List.filterNotNull() function returns a list containing all values that are not null.

Program

fun main() {
    val mixedList = listOf(1, null, "apple", 3, null, "orange", null, 7)

    val notNullValues = mixedList.filterNotNull()

    println(notNullValues)
}

Output

[1, apple, 3, orange, 7]