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