The filterNotNullTo() extension function in Kotlin filters elements in a set, appending all elements that are not null to the given destination collection.
The syntax of Set.filterNotNullTo() extension function is:
fun <C : MutableCollection<in T>, T : Any> Set<T?>.filterNotNullTo(destination: C): C
This filterNotNullTo() extension function of Set appends all elements that are not null to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the non-null elements will be appended. |
Set.filterNotNullTo() returns value of type C
.
Using filterNotNullTo() to filter elements in a set, appending non-null values to a list.
For example,
fun main() {
val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
val nonNullList = mutableListOf<Int>()
mixedSet.filterNotNullTo(nonNullList)
println(nonNullList)
}
[1, 2, 4, 6]
Using filterNotNullTo() to filter elements in a set, appending non-null values to another set.
For example,
fun main() {
val mixedSet: Set<String?> = setOf("a", null, "b", "c", null)
val nonNullSet = mutableSetOf<String>()
mixedSet.filterNotNullTo(nonNullSet)
println(nonNullSet)
}
["a", "b", "c"]
Using filterNotNullTo() to filter elements in a set containing mixed types, appending non-null values to a list.
For example,
fun main() {
val mixedSet: Set<Any?> = setOf(1, "two", null, 3.0, null, "four")
val nonNullList = mutableListOf<Any>()
mixedSet.filterNotNullTo(nonNullList)
println(nonNullList)
}
[1, "two", 3.0, "four"]
In this Kotlin tutorial, we learned about filterNotNullTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.