Kotlin Tutorials

Kotlin Map mapTo()
Syntax & Examples

Syntax of Map.mapTo()

The syntax of Map.mapTo() extension function is:

fun <K, V, R, C : MutableCollection<in R>> Map<out K, V>.mapTo( destination: C, transform: (Entry<K, V>) -> R ): C

This mapTo() extension function of Map applies the given transform function to each entry of the original map and appends the results to the given destination.



✐ Examples

1 Map key-value pairs to strings

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 mapTo() function to apply a transformation to each entry in map1, concatenating the key and value into a string.
  • The 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.mapTo(destination) { entry -> "Key: ${entry.key}, Value: ${entry.value}" }
    println(destination)
}

Output

[Key: 1, Value: apple, Key: 2, Value: banana, Key: 3, Value: cherry]

2 Double values or assign 0 if null

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 mapTo() function to apply a transformation to each entry in map2, doubling the value if it's not null, otherwise assigning 0.
  • The 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.mapTo(destination) { entry -> entry.value?.let { it * 2 } ?: 0 }
    println(destination)
}

Output

[2, 4, 6]

3 Map keys to strings

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 mapTo() function to apply a transformation to each entry in map3, mapping each key to its string representation.
  • The 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<String>()
    map3.mapTo(destination) { entry -> entry.key }
    println(destination)
}

Output

[apple, banana, cherry]

Summary

In this Kotlin tutorial, we learned about mapTo() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.