Sets and Maps
Two new questions at the café: "How many different customers came in today?" and "What does a chai cost?" A list can answer both, but awkwardly. A set is built for the first question and a map for the second.
The rule
Set: each value once. Map: each key once, pointing to a value.
Sets ignore duplicates. Adding something already there changes nothing.
val visitors = mutableSetOf("Ravi", "Mei")
visitors.add("Ravi") // returns false: already there
println(visitors) // [Ravi, Mei]
println(visitors.size) // 2
println("Mei" in visitors) // trueKotlin's default sets remember the order you added things, but order does not matter for equality: setOf(1, 2) == setOf(2, 1) is true. Sets also answer "who is in both?" with intersect, and "everyone together" with union.
Maps store key → value pairs. Each key appears once; the word to builds a pair.
val prices = mutableMapOf("latte" to 3.5, "chai" to 2.0)
println(prices["chai"]) // 2.0
println(prices["tea"]) // null: no such key
println(prices.getOrDefault("tea", 0.0)) // 0.0
prices["tea"] = 2.5 // adds a new key
prices["latte"] = 3.8 // replaces the old value
println(prices) // {latte=3.8, chai=2.0, tea=2.5}Because a key may be missing, prices["chai"] has the nullable type Double?. If you are certain the key exists, prices.getValue("chai") returns a plain Double, and throws NoSuchElementException if you were wrong.
To walk through a map, unpack each entry:
for ((drink, price) in prices) {
println("$drink costs $price")
}The shortcut
Pick by the question you will ask most:
- "Is X in here?" or "how many distinct?" → set.
- "What goes with X?" → map, with X as the key.
- "What is at position 3?" or "keep duplicates and order" → list.
The question
"How many stamps does Mei have?" Given a name, find a number.
Drills
Answer fast — trust the rule.
What is setOf("latte", "chai", "latte").size?
val prices = mapOf("latte" to 3.5). What is prices["mocha"]?
What does mapOf("chai" to 2.0, "chai" to 2.4) contain?
Which call throws if the key "tea" is missing?
Remember
- Sets store each value once; maps store each key once with its value.
map[key]returns null for a missing key;getOrDefaultsupplies a fallback.- Choose by the question: membership → set, lookup → map, position → list.
