The syntax of Map.mapNotNullTo() extension function is:
fun <K, V, R : Any, C : MutableCollection<in R>> Map<out K, V>.mapNotNullTo( destination: C, transform: (Entry<K, V>) -> R? ): C
This mapNotNullTo() extension function of Map applies the given transform function to each entry in the original map and appends only the non-null results to the given destination.
In this example,
map1
with integer keys and string values.destination
.mapNotNullTo()
function to apply a transformation to each entry in map1
, filtering out entries where the key is not even.destination
list.destination
list to standard output.fun main(args: Array<String>) {
val map1 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
val destination = mutableListOf<String>()
map1.mapNotNullTo(destination) { entry -> if (entry.key % 2 == 0) entry.value else null }
println(destination)
}
[banana]
In this example,
map2
with string keys and integer values.destination
.mapNotNullTo()
function to apply a transformation to each entry in map2
, doubling the value if it's not null.destination
list.destination
list to standard output.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val destination = mutableListOf<Int>()
map2.mapNotNullTo(destination) { entry -> entry.value?.let { it * 2 } }
println(destination)
}
[2, 4, 6]
In this example,
map3
with string keys and integer values.destination
.mapNotNullTo()
function to apply a transformation to each entry in map3
, mapping the key to its length.destination
list.destination
list to standard output.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val destination = mutableListOf<Int>()
map3.mapNotNullTo(destination) { entry -> entry.key.length }
println(destination)
}
[5, 6, 6]
In this Kotlin tutorial, we learned about mapNotNullTo() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.