Careeroza
Maps
Key-Value Pairs
Example
A Map stores key-value pairs. Keys are unique. "key" to value creates a pair. mapOf keeps insertion order.
fun main() {
val prices = mapOf("Dosa" to 60, "Idli" to 40, "Vada" to 30)
println(prices)
println(prices["Dosa"]) // value or null
println(prices["Pizza"])
println(prices.getOrDefault("Pizza", 0))
println(prices.keys)
println(prices.values)
println("Idli" in prices) // checks keys
println(prices.size)
}Output
{Dosa=60, Idli=40, Vada=30}
60
null
0
[Dosa, Idli, Vada]
[60, 40, 30]
true
3Mutable Maps and Iteration
Example
mutableMapOf lets you add, update and remove entries. Loop with destructuring (key, value).
fun main() {
val cart = mutableMapOf<String, Int>() // item -> quantity
cart["Dosa"] = 2
cart["Coffee"] = 1
cart["Dosa"] = 3 // update
cart["Vada"] = cart.getOrDefault("Vada", 0) + 1
cart.remove("Coffee")
for ((item, qty) in cart) {
println("$item x $qty")
}
println(cart)
}Output
Dosa x 3
Vada x 1
{Dosa=3, Vada=1}Note: map[key] returns a nullable type (Int?) because the key might be missing. Use getOrDefault, ?: or getValue (throws if missing).