The mapNotNull() extension function in Kotlin returns a list containing only the non-null results of applying the given transform function to each element in the original set.
The syntax of Set.mapNotNull() extension function is:
fun <T, R : Any> Set<T>.mapNotNull(transform: (T) -> R?): List<R>
This mapNotNull() extension function of Set returns a list containing only the non-null results of applying the given transform function to each element in the original collection.
Parameter | Optional/Required | Description |
---|---|---|
transform | required | A function that takes an element and returns the transformed result, which may be null. |
Set.mapNotNull() returns value of type List
.
Using mapNotNull() to transform a set of integers by doubling each element, and filtering out null results.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val doubled = numbers.mapNotNull { if (it % 2 == 0) it * 2 else null }
println(doubled)
}
[4, 8]
Using mapNotNull() to transform a set of strings by getting the length of each string, and filtering out null results.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val lengths = strings.mapNotNull { if (it.length > 3) it.length else null }
println(lengths)
}
[5]
Using mapNotNull() to transform a set of custom objects by extracting a specific property, and filtering out null results.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val names = people.mapNotNull { if (it.age > 30) it.name else null }
println(names)
}
[Charlie]
In this Kotlin tutorial, we learned about mapNotNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.