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.
- Consider that we are given a list of values in mixedList. This list can contain values of any type including null values.
- Call filterNotNull() function on the mixedList.
- 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]