What is the smartest way to copy a Map in Kotlin?
27,546
Solution 1
Just use the HashMap
constructor:
val original = hashMapOf(1 to "x")
val copy = HashMap(original)
Update for Kotlin 1.1:
Since Kotlin 1.1, the extension functions Map.toMap
and Map.toMutableMap
create copies.
Solution 2
Use putAll
method:
val map = mapOf("1" to 1, "2" to 2)
val copy = hashMapOf<String, Int>()
copy.putAll(map)
Or:
val map = mapOf("1" to 1, "2" to 2)
val copy = map + mapOf<String, Int>() // preset
Your way also looks idiomatic to me.
Solution 3
The proposed way of doing this is:
map.toList().toMap()
However, the java's method is 2 to 3 times faster:
(map as LinkedHashMap).clone()
Anyway, if it bothers you that there is no unified way of cloning Kotlin's collections (and there is in Java!), vote here: https://youtrack.jetbrains.com/issue/KT-11221
![N. Kudryavtsev](https://i.stack.imgur.com/aYtz9.png?s=256&g=1)
Comments
-
N. Kudryavtsev over 3 years
I'd like to get a new instance of some Map with the same content but Map doesn't have a built-in
copy
method. I can do something like this:val newInst = someMap.map { it.toPair() }.toMap()
But it looks rather ugly. Is there any more smarter way to do this?