The filterNotNull() extension function in Kotlin filters elements in a set, returning a list of elements that are not null.
The syntax of Set.filterNotNull() extension function is:
fun <T : Any> Set<T?>.filterNotNull(): List<T>
This filterNotNull() extension function of Set returns a list containing all elements that are not null.
Set.filterNotNull() returns value of type List
.
Using filterNotNull() to filter elements in a set, excluding null values.
For example,
fun main() {
val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
val nonNulls = mixedSet.filterNotNull()
println(nonNulls)
}
[1, 2, 4, 6]
Using filterNotNull() to filter elements in a set, excluding null values.
For example,
fun main() {
val mixedSet: Set<String?> = setOf("a", null, "b", "c", null)
val nonNullStrings = mixedSet.filterNotNull()
println(nonNullStrings)
}
["a", "b", "c"]
Using filterNotNull() to filter elements in a set containing mixed types, excluding null values.
For example,
fun main() {
val mixedSet: Set<Any?> = setOf(1, "two", null, 3.0, null, "four")
val nonNullElements = mixedSet.filterNotNull()
println(nonNullElements)
}
[1, "two", 3.0, "four"]
In this Kotlin tutorial, we learned about filterNotNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.