1. Overview

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

As of Kotlin 1.1, we can use the toMap() extension function to copy all the entries of a Map to another one:

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)

Please note that these are only creating a shallow copy of the given Map. That is, the two Map instances are different objects in the Java heap but their contents are the same objects:

assertSame(copied["name"], bookInfo["name"])

3. Conclusion

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.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.