Kotlin Maps
A map stores data as key-value pairs. Each key is unique, and each key maps to exactly one value. Think of a map like a dictionary: each word (key) has its own definition (value). Maps are ideal when you need to look up data by a name or identifier.
Creating a Map
val ages = mapOf("Alice" to 30, "Bob" to 25, "Carol" to 28)
val scores = mapOf(
"Math" to 92,
"English" to 88,
"Science" to 95
)Map Structure
mapOf("Alice" to 30, "Bob" to 25, "Carol" to 28)
Key │ Value
─────────┼───────
"Alice" │ 30
"Bob" │ 25
"Carol" │ 28
Access by key: map["Alice"] → 30
Accessing Values
val capitals = mapOf("India" to "New Delhi", "Japan" to "Tokyo", "France" to "Paris")
println(capitals["India"]) // New Delhi
println(capitals["Japan"]) // Tokyo
println(capitals["Germany"]) // null (key not found)
println(capitals.getValue("France")) // Paris
// capitals.getValue("Germany") // throws NoSuchElementException
println(capitals.getOrDefault("Germany", "Unknown")) // Unknown
println(capitals.getOrElse("Germany") { "Not in map" }) // Not in mapMap Properties
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map.size) // 3
println(map.isEmpty()) // false
println(map.containsKey("b")) // true
println(map.containsValue(2)) // true
println("a" in map) // true (checks key)Iterating a Map
val prices = mapOf("Apple" to 80, "Mango" to 120, "Banana" to 40)
// Iterate key-value pairs
for ((item, price) in prices) {
println("$item costs ₹$price")
}
// Keys only
for (key in prices.keys) { println(key) }
// Values only
for (value in prices.values) { println(value) }Mutable Map
val inventory = mutableMapOf("Pens" to 50, "Notebooks" to 30)
// Add new entry
inventory["Stapler"] = 10
// Update existing
inventory["Pens"] = 45
// Remove
inventory.remove("Notebooks")
println(inventory) // {Pens=45, Stapler=10}Useful Map Functions
val marks = mapOf("Alice" to 88, "Bob" to 72, "Carol" to 95, "Dan" to 60)
// Filter entries where value meets condition
val toppers = marks.filter { it.value >= 85 }
println(toppers) // {Alice=88, Carol=95}
// Transform values
val scaled = marks.mapValues { it.value * 1.1 }
println(scaled) // {Alice=96.8, Bob=79.2, Carol=104.5, Dan=66.0}
// Transform keys
val keysUpper = marks.mapKeys { it.key.uppercase() }
println(keysUpper) // {ALICE=88, BOB=72, CAROL=95, DAN=60}Practical Example: Word Frequency Counter
fun main() {
val sentence = "kotlin is fun kotlin is easy kotlin is great"
val words = sentence.split(" ")
val frequency = mutableMapOf()
for (word in words) {
frequency[word] = (frequency[word] ?: 0) + 1
}
println("Word Frequencies:")
frequency.entries.sortedByDescending { it.value }.forEach {
println(" ${it.key.padEnd(8)} → ${it.value} times")
}
} Output:
Word Frequencies:
kotlin → 3 times
is → 3 times
fun → 1 times
easy → 1 times
great → 1 times