Map — mapOf() / mutableMapOf()
| Since: | Kotlin 1.0(2016) |
|---|
In Kotlin, use mapOf() to create an immutable map of key-value pairs, and mutableMapOf() to create a mutable map. Use the to infix function to create pairs, and the [] operator or get() to retrieve values.
Syntax
val capitals = mapOf("Japan" to "Tokyo", "France" to "Paris")
val scores = mutableMapOf("item_a" to 85, "item_b" to 72)
scores["item_c"] = 91 // Add or update
scores.remove("item_b") // Remove
// Retrieve values
val tokyo = capitals["Japan"] // "Tokyo" (null if not found)
val default = capitals.getOrDefault("Germany", "Unknown") // "Unknown"
val safe = capitals.getOrElse("Germany") { "Unknown" } // "Unknown"
Method List
| Method / Property | Description |
|---|---|
| mapOf(k to v, ...) | Creates an immutable map. |
| mutableMapOf(k to v, ...) | Creates a mutable map. |
| map[key] | Returns the value for the key, or null if not found. |
| map.get(key) | Equivalent to []. |
| map.getOrDefault(key, default) | Returns the default value if the key is not found. |
| map.getOrElse(key) { lambda } | Returns the lambda result if the key is not found. |
| map.containsKey(key) | Checks whether the key exists (also writable as key in map). |
| map.keys / .values / .entries | Returns a collection of keys, values, or entries. |
| MutableMap[key] = value | Adds or updates a value. |
| MutableMap.remove(key) | Removes the key and its associated value. |
| MutableMap.putIfAbsent(key, value) | Adds the entry only if the key does not already exist. |
| map.map { (k, v) -> } | Returns a new list by transforming each entry. |
| map.filter { (k, v) -> } | Returns a map containing only entries that match the condition. |
Sample Code
sample_map_create.kt
fun main() {
// Basic mapOf
val capitals = mapOf(
"Japan" to "Tokyo",
"France" to "Paris",
"UK" to "London",
"Germany" to "Berlin"
)
// Key access
println(capitals["Japan"]) // Tokyo
println(capitals["Spain"]) // null
println(capitals.getOrDefault("Spain", "Unknown")) // Unknown
// Check existence
println("Japan" in capitals) // true
println(capitals.containsKey("China")) // false
println()
// keys / values / entries
println("Countries: ${capitals.keys}")
println("Capitals: ${capitals.values}")
capitals.entries.forEach { (country, capital) ->
println(" $country → $capital")
}
println()
// Mutable map
val inventory = mutableMapOf("Apple" to 10, "Banana" to 5)
inventory["Orange"] = 8 // Add
inventory["Apple"] = 15 // Update
inventory.remove("Banana") // Remove
println("Inventory: $inventory")
// putIfAbsent — adds only if the key does not exist
inventory.putIfAbsent("Apple", 999) // Already exists, so skipped
inventory.putIfAbsent("Grape", 3) // Added
println("After adding: $inventory")
println()
// Key-value map
val tags = mapOf(
"item_a" to "category_x",
"item_b" to "category_y",
"item_c" to "category_z"
)
println("item_a tag: ${tags["item_a"]}")
println()
// Transform a map with map / filter
val prices = mapOf("Apple" to 150, "Banana" to 100, "Orange" to 200, "Grape" to 500)
// Keep only items priced over 150
val expensive = prices.filter { (_, price) -> price > 150 }
println("Over 150: $expensive")
val raised = prices.mapValues { (_, price) -> (price * 1.1).toInt() }
println("After 10% increase: $raised")
}
map_create.kt
kotlinc map_create.kt -include-runtime -d map_create.jar
java -jar map_create.jar
Tokyo
null
Unknown
true
false
Countries: [Japan, France, UK, Germany]
Capitals: [Tokyo, Paris, London, Berlin]
Japan → Tokyo
France → Paris
UK → London
Germany → Berlin
Inventory: {Apple=15, Orange=8}
After adding: {Apple=15, Orange=8, Grape=3}
item_a tag: category_x
Over 150: {Orange=200, Grape=500}
After 10% increase: {Apple=165, Banana=110, Orange=220, Grape=550}
Common Mistakes
The following covers common mistakes when adding to an immutable map, handling null values from map access, and the difference between manual Pair creation and the to infix function.
| Mistake | Cause and Fix |
|---|---|
Trying to add elements to an immutable map created with mapOf | mapOf produces a read-only map. Use mutableMapOf when you need to add or update entries. |
Not accounting for map[key] returning null | Accessing a missing key returns null, which causes a NullPointerException if used directly. Use getOrDefault or the Elvis operator ?: for safe access. |
Using map[key] != null to check for key existence | This check returns false for entries whose value is null, even though the key exists. Use containsKey to test for key presence. |
Using Pair("item_a", 85) instead of the infix function | Both compile, but the to infix function — "item_a" to 85 — is more readable and idiomatic Kotlin. |
The sample code below demonstrates the correct usage.
sample_map_create_mistakes.kt
fun main() {
val scores = mapOf("item_a" to 85, "item_b" to 72)
// Use mutableMapOf when you need to modify the map
val mutableScores = mutableMapOf("item_a" to 85, "item_b" to 72)
mutableScores["item_c"] = 91
println("After adding: $mutableScores")
// Use getOrDefault or the ?: operator for safe access
val value = scores["item_d"] // null
val safeValue = scores.getOrDefault("item_d", "Unknown")
println("item_d value: $safeValue")
val nullable = mapOf("item_a" to null)
println(nullable["item_a"] != null) // false (value is null)
println(nullable.containsKey("item_a")) // true (key exists)
// The to infix function is the idiomatic Kotlin style
val m1 = mapOf(Pair("item_a", 85)) // Works but verbose
val m2 = mapOf("item_a" to 85)
println("m1 == m2: ${m1 == m2}") // true
}
The command looks like this:
kotlinc sample_map_create_mistakes.kt -include-runtime -d sample_map_create_mistakes.jar
java -jar sample_map_create_mistakes.jar
After adding: {item_a=85, item_b=72, item_c=91}
item_d value: Unknown
false
true
m1 == m2: true
Notes
Kotlin map operations support the same functional style as list operations. You can use mapValues() to transform only the values, or filter() to narrow down entries by key or value conditions.
Maps use Java's LinkedHashMap internally, so insertion order is preserved. Use sortedMapOf() if you need keys in alphabetical order.
For set operations, see Set — setOf() / mutableSetOf(). For list basics, see List — listOf() / mutableListOf().
If you find any errors or copyright issues, please contact us.