← Back to Kotlin Course | Chapter 8: Collections | Lesson 3 of 7

Set and Map

A Set is a bag that refuses to hold the same item twice, and a Map is like a dictionary matching each key to exactly one value.

Creating and Using a Set

setOf(...) builds a collection that automatically discards duplicate values, useful whenever uniqueness matters more than order or position.

Example: Creating and Using a Set

markup
fun main() {
    val uniqueNumbers = setOf(1, 2, 2, 3, 3, 3)
    println(uniqueNumbers)
    println("Contains 2: ${uniqueNumbers.contains(2)}")
}

Creating and Using a Map

mapOf(...) builds a read-only collection of key-value pairs, constructed using the infix to function to pair each key with its value.

Example: Creating and Using a Map

markup
fun main() {
    val ages = mapOf("Ana" to 30, "Bo" to 25)
    println(ages)
    println("Ana's age: ${ages["Ana"]}")
}

Handling Missing Map Keys

Looking up a key that doesn't exist with map[key] returns null rather than throwing, so the result is naturally a nullable type that should be handled with ?: or a null check.

Example: Handling Missing Map Keys

markup
fun main() {
    val ages = mapOf("Ana" to 30)
    val boAge = ages["Bo"] ?: -1
    println("Bo's age (or -1 if missing): $boAge")
}

Mutable Sets and Maps

mutableSetOf() and mutableMapOf() create their mutable counterparts, supporting .add() for sets and .put()/map[key] = value for maps after creation.

Example: Mutable Sets and Maps

markup
fun main() {
    val tags = mutableSetOf("kotlin", "jvm")
    tags.add("android")
    tags.add("kotlin") // duplicate, ignored

    val scores = mutableMapOf("Ana" to 90)
    scores["Bo"] = 85

    println(tags)
    println(scores)
}
Common Mistakes
  1. Expecting a Set to preserve insertion order like a List; a plain HashSet-backed setOf() does not guarantee order (though LinkedHashSet does).
  2. Using square-bracket access on a Map for a missing key and getting null unexpectedly instead of an exception, then not handling that null.
  3. Confusing mapOf() (read-only) with mutableMapOf() when the map actually needs to be modified after creation.
Chapter Summary
  • setOf(...) creates a read-only Set that automatically removes duplicate values.
  • mapOf(...) creates a read-only Map of key-value pairs, built using the key to value syntax.
  • Accessing a missing key in a Map with map[key] returns null rather than throwing.
  • mutableSetOf() and mutableMapOf() are the mutable counterparts supporting .add()/.put() and removal.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.