To copy a map in Kotlin, you can use the `toMap()` method or the `copy` function to create a new map with the same key-value pairs as the original map. These methods provide straightforward ways to duplicate a map.
We can copy a map in Kotlin using the `toMap()` method, which creates a new map with the same key-value pairs as the original map.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.toMap()
method to create a new map named copiedMap
that contains the same key-value pairs as originalMap
.println
function to verify the copy.fun main() {
// Declare and initialize a map
val originalMap = mapOf("one" to 1, "two" to 2, "three" to 3)
// Copy the map using the toMap() method
val copiedMap = originalMap.toMap()
// Print the copied map
println("Copied Map: $copiedMap")
}
Copied Map: {one=1, two=2, three=3}
We can also copy a mutable map in Kotlin using the `toMutableMap()` method, which creates a new mutable map with the same key-value pairs as the original map.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.toMutableMap()
method to create a new mutable map named copiedMap
that contains the same key-value pairs as originalMap
.println
function to verify the copy.fun main() {
// Declare and initialize a mutable map
val originalMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
// Copy the map using the toMutableMap() method
val copiedMap = originalMap.toMutableMap()
// Print the copied map
println("Copied Map: $copiedMap")
}
Copied Map: {one=1, two=2, three=3}
We can copy a map in Kotlin and modify its values during the copying process by iterating over the original map and applying transformations to the values.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.mapValues
function to create a new map named copiedMap
, modifying the values during the copying process (e.g., multiplying each value by 2).println
function to verify the copy.fun main() {
// Declare and initialize a map
val originalMap = mapOf("one" to 1, "two" to 2, "three" to 3)
// Copy the map and modify values
val copiedMap = originalMap.mapValues { it.value * 2 }
// Print the copied map
println("Copied Map: $copiedMap")
}
Copied Map: {one=2, two=4, three=6}
In this tutorial, we learned How to Copy a Map in Kotlin language with well detailed examples.