In this short tutorial, we’re going to learn a few ways to copy all the entries of a Map to another Map in Kotlin.
2. Copying a Map
val bookInfo = mapOf("name" to "1984", "author" to "Orwell") val copied = bookInfo.toMap() assertThat(copied).isNotSameAs(bookInfo) assertThat(copied).containsAllEntriesOf(bookInfo)
Of course, after the copy is done, we won’t be able to change the copied Map contents, as it’s immutable. In order to be able to change the Map after the copy, we can use the toMutableMap() extension function:
val mutableCopy = bookInfo.toMutableMap(); assertThat(mutableCopy).containsAllEntriesOf(bookInfo)
It’s also possible to populate a pre-existing Map instance with the contents of another one:
val destination = mutableMapOf<String, String>() bookInfo.toMap(destination) assertThat(destination).containsAllEntriesOf(bookInfo)
In the above example, we’re passing another Map to the toMap(map) extension function. This way, we’re copying all the entries of the receiving Map (bookInfo) to the given one.
Before Kotlin 1.1, we can use the underlying Map implementation directly to achieve the same thing. For instance, here, we’re using the java.util.HashMap constructor to copy everything from another Map:
val copied = java.util.HashMap(bookInfo) assertThat(copied).containsAllEntriesOf(bookInfo)
In this tutorial, we learned a couple of ways to copy the contents of a Map to another one in Kotlin.
As usual, all the examples are available over on GitHub.