1. Overview

In this tutorial, we’ll look at some ways to initialize a Map in Kotlin. First, we’ll go through methods like mapOf and mutableMapOf.

Then, we’ll look at some functions to create more specific map implementations.

2. Using mapOf

The most common way to initialize a map is to use the mapOf factory method. Using mapOf, we can create an immutable Map with some initial entries:

val mapWithValues = mapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")

Note that we don’t need to specify the type explicitly here. In contrast, this isn’t the case when we create an empty map:

val mapWithoutValues = mapOf<String, String>()

This creates an empty immutable map of the specified type. This is the same as using the emptyMap:

val emptyMap = emptyMap<String, String>()

3. Using mutableMapOf

Similarly, we can use the mutableMapOf factory method to create a MutableMap:

val emptyMutableMap = mutableMapOf<String, String>()
emptyMutableMap["Key"] = "Value"

Alternatively, we can initialize the map with some values and still be able to add/modify the map later:

val mutableMap = mutableMapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")
mutableMap["Key3"] = "Value10" // modify value
mutableMap["Key4"] = "Value4" // add entry
mutableMap.remove("Key1") // delete existing value

4. Using hashMapOf

With the hashMapOf function, we can create a HashMap:

val hashMap = hashMapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")

As we know, HashMap is mutable. Hence, we can add/modify its entries post-creation:

hashMap["Key3"] = "Value10" // modify value
hashMap["Key4"] = "Value4" // add entry
hashMap.remove("Key1") // delete existing value

5. Using sortedMapOf and linkedMapOf

In Kotlin, we also have access to functions to create other specific maps:

val sortedMap = sortedMapOf("Key3" to "Value3", "Key1" to "Value1", "Key2" to "Value2")
val linkedMap = linkedMapOf("Key3" to "Value3", "Key1" to "Value1", "Key2" to "Value2")

As the name suggests, sortedMapOf creates a mutable SortedMap. Likewise, the linkedMapOf function creates a LinkedMap object.

6. Conclusion

Kotlin has a variety of functions to create maps. The most commonly used are the mapOf and mutableMapOf.

On the other hand, some use cases (such as legacy code bases) may require specific maps. For these cases, we also have access to more specific factory functions.

As always, the code samples 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.