Clone a map in Kotlin
This article explores different ways to clone a map in Kotlin. The solution should create a copy of all the mappings from the given map to the new map.
1. Using toMap() function
You can use the native methods toMap() and toMutableMap() to return a copy of a map. The toMap() function returns an immutable instance of the map, while toMutableMap() function returns a mutable instance.
|
1 2 3 4 5 6 7 |
fun main() { val map: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val clone: Map<Int, String> = map.toMutableMap() println(clone) // {1=one, 2=two, 3=three} } |
2. Using Copy Constructor
Another simple and fairly efficient solution is to use the HashMap‘s copy constructor, which creates a new map as a copy of an existing map.
|
1 2 3 4 5 6 7 |
fun main() { val map: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val clone: Map<Int, String> = HashMap(map) println(clone) // {1=one, 2=two, 3=three} } |
3. Using putAll() function
Alternatively, you can also use the putAll() function to copy all mappings from the original map to an empty map.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <K, V> clone(original: Map<K, V>): MutableMap<K, V> { val copy: MutableMap<K, V> = HashMap() copy.putAll(original) return copy } fun main() { val map: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val clone: Map<Int, String> = clone(map) println(clone) // {1=one, 2=two, 3=three} } |
4. Custom Routine
Finally, you can write your own routine for this simple task. The idea is to iterate over the map and add each mapping from key K to value V in the specified map.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <K, V> clone(original: Map<K, V>): MutableMap<K, V> { val copy: MutableMap<K, V> = HashMap() original.forEach { (key, value) -> copy[key] = value } return copy } fun main() { val map: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val clone: Map<Int, String> = clone(map) println(clone) // {1=one, 2=two, 3=three} } |
That’s all about cloning a map in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)