Kotlin Tutorials

Kotlin Map mapNotNullTo()
Syntax & Examples

Syntax of Map.mapNotNullTo()

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.



✐ Examples

1 Filter values based on key condition

In this example,

  • We create a map named map1 with integer keys and string values.
  • We initialize an empty mutable list named destination.
  • We use the mapNotNullTo() function to apply a transformation to each entry in map1, filtering out entries where the key is not even.
  • The non-null results of the transformation are appended to the destination list.
  • We print the destination list to standard output.

Kotlin Program

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)
}

Output

[banana]

2 Double values and filter out nulls

In this example,

  • We create a map named map2 with string keys and integer values.
  • We initialize an empty mutable list named destination.
  • We use the mapNotNullTo() function to apply a transformation to each entry in map2, doubling the value if it's not null.
  • The non-null results of the transformation are appended to the destination list.
  • We print the destination list to standard output.

Kotlin Program

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)
}

Output

[2, 4, 6]

3 Map keys to their lengths

In this example,

  • We create a map named map3 with string keys and integer values.
  • We initialize an empty mutable list named destination.
  • We use the mapNotNullTo() function to apply a transformation to each entry in map3, mapping the key to its length.
  • The non-null results of the transformation are appended to the destination list.
  • We print the destination list to standard output.

Kotlin Program

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)
}

Output

[5, 6, 6]

Summary

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.