Beginner 8 min readKotlin 2.0
Kotlin Map — Key-Value Pairs with mapOf and mutableMapOf
A Map stores key-value pairs. Each key is unique. Kotlin has read-only (mapOf) and mutable (mutableMapOf) maps.
What You Will Learn
- Create maps with mapOf
- Access values by key
- Add and update entries with mutableMapOf
- Iterate over map entries
- Check key and value membership
Read-Only Map with mapOf
Create key-value pairs using the to infix function.
mapOf
kotlin
fun main() {
val capitals = mapOf(
"India" to "New Delhi",
"France" to "Paris",
"Japan" to "Tokyo"
)
println(capitals["India"])
println(capitals["Germany"]) // key not found
println(capitals.size)
println("France" in capitals)
}Output
New Delhi
null
3
true
"India" to "New Delhi" is the Pair syntax. capitals["India"] retrieves the value. capitals["Germany"] returns null because the key does not exist.
Beginner Tip: Use getOrDefault("Germany", "Unknown") to provide a fallback when a key might not exist.
Mutable Map
mutableMapOf lets you add, update, and remove entries.
mutableMapOf
kotlin
fun main() {
val scores = mutableMapOf("Alice" to 85, "Bob" to 90)
scores["Carol"] = 78 // add new entry
scores["Alice"] = 92 // update existing
scores.remove("Bob")
println(scores)
}Output
{Alice=92, Carol=78}
scores["key"] = value adds or updates. .remove() deletes by key. Bob is removed.
Iterating a Map
Iterate over entries, keys, or values.
Iterating
kotlin
fun main() {
val prices = mapOf("Coffee" to 2.5, "Tea" to 1.8, "Juice" to 3.0)
for ((item, price) in prices) {
println("$item: $$price")
}
println("Keys: ${prices.keys}")
println("Values: ${prices.values}")
}Output
Coffee: $2.5
Tea: $1.8
Juice: $3.0
Keys: [Coffee, Tea, Juice]
Values: [2.5, 1.8, 3.0]
Destructuring (item, price) unpacks each Map.Entry. .keys returns the set of keys. .values returns a collection of values.
Practice Exercise
Exercisepredict output
What prints? val m = mapOf("a" to 1, "b" to 2) println(m["a"]) println(m["c"])
Quick Quiz
Quick Quiz
What does the to keyword do in Kotlin maps?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review