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.
In this example,
map1
with integer keys and string values.destination
.mapTo()
function to apply a transformation to each entry in map1
, concatenating the key and value into a string.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.mapTo(destination) { entry -> "Key: ${entry.key}, Value: ${entry.value}" }
println(destination)
}
[Key: 1, Value: apple, Key: 2, Value: banana, Key: 3, Value: cherry]
In this example,
map2
with string keys and integer values.destination
.mapTo()
function to apply a transformation to each entry in map2
, doubling the value if it's not null, otherwise assigning 0.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.mapTo(destination) { entry -> entry.value?.let { it * 2 } ?: 0 }
println(destination)
}
[2, 4, 6]
In this example,
map3
with string keys and integer values.destination
.mapTo()
function to apply a transformation to each entry in map3
, mapping each key to its string representation.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<String>()
map3.mapTo(destination) { entry -> entry.key }
println(destination)
}
[apple, banana, cherry]
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.