Skip to the workspace
Pebellslearn by building
Collections, Ranges and Sequences  ›  Lesson

Sets and Maps

Maps 15 minA set holds each value at most once, and a map links unique keys to values, returning null when asked for a key it does not have.

kotlin / Sets and Maps

Explore each scene at your own pace.

01 · The rule

The rule

Sets and Maps

A set holds each value at most once, and a map links unique keys to values, returning null when asked for a key it does not have.

Represent membership and keyed lookup while accounting for duplicates or missing entries.

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)      // true

Kotlin'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")
}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.