Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the smartest way to copy a Map in Kotlin?

Tags:

hashmap

kotlin

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?

like image 759
N. Kudryavtsev Avatar asked Feb 27 '16 16:02

N. Kudryavtsev


People also ask

What is difference between HashMap and map in Kotlin?

A mutable map is a map that is mutable. It's an interface. And it has plenty of implementstions (HashMap, TreeMap, ConcurrentHashMap, etc.). A HashMap is a specific implementation of a (Mutable)Map.


3 Answers

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.

like image 146
Ingo Kegel Avatar answered Oct 23 '22 02:10

Ingo Kegel


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.

like image 9
marcospereira Avatar answered Oct 23 '22 02:10

marcospereira


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

like image 2
voddan Avatar answered Oct 23 '22 00:10

voddan