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 ): C
This 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
list1
containing integers and null values. - We create an empty mutable list named
result
to store the non-null elements. - We use the
filterNotNullTo
function onlist1
to filter out null elements and append non-null elements toresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
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
list2
containing strings and null values. - We create an empty mutable list named
result
to store the non-null strings. - We use the
filterNotNullTo
function onlist2
to filter out null elements and append non-null strings toresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
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
list3
containing characters and null values. - We create an empty mutable list named
result
to store the non-null characters. - We use the
filterNotNullTo
function onlist3
to filter out null elements and append non-null characters toresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
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.