Kotlin List filterNotNullTo()
Syntax & Examples
Syntax of List.filterNotNullTo()
The syntax of List.filterNotNullTo() extension function is:
fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo( destination: C ): CThis filterNotNullTo() extension function of List appends all elements that are not null to the given destination.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing integers and null values. - We create an empty mutable list named
resultto store the non-null elements. - We use the
filterNotNullTofunction onlist1to filter out null elements and append non-null elements toresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, null, 3, null, 5)
val result = mutableListOf<Int>()
list1.filterNotNullTo(result)
println(result)
}Output
[1, 3, 5]
2 Example
In this example,
- We create a list named
list2containing strings and null values. - We create an empty mutable list named
resultto store the non-null strings. - We use the
filterNotNullTofunction onlist2to filter out null elements and append non-null strings toresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", null, "cherry", "date")
val result = mutableListOf<String>()
list2.filterNotNullTo(result)
println(result)
}Output
[apple, cherry, date]
3 Example
In this example,
- We create a list named
list3containing characters and null values. - We create an empty mutable list named
resultto store the non-null characters. - We use the
filterNotNullTofunction onlist3to filter out null elements and append non-null characters toresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf('a', null, 'c', null, 'e')
val result = mutableListOf<Char>()
list3.filterNotNullTo(result)
println(result)
}Output
[a, c, e]
Summary
In this Kotlin tutorial, we learned about filterNotNullTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.