CodeBlanks Logo Icon CodeBlanks

Summary - Maps and Sets

Combine Set and Map to write a phone book.

Summary: phone book with a set and a map

In this summary you will build a phone book. You use a MutableSet<String> to guarantee names are unique, and a MutableMap<String, String> to bind each name to a number.

val names = mutableSetOf("Ava", "Liam")
val phones = mutableMapOf("Ava" to "5551", "Liam" to "5552")
println(names)
println(phones)

The set drops duplicate names; the map binds a name to a number for quick lookup. Together they form a unique-key lookup table.

Practice Build and print the phone book

Create a mutableSetOf("Ava", "Liam") and a mutableMapOf("Ava" to "5551", "Liam" to "5552"). Print the set first with println(names), then the map with println(phones).

Starter code

Main.kt
fun main() {
    // Phone book: hold unique names in a set, numbers in a map
    // Add two people and print the set first, then the map
}

Sample solution

Main.kt
fun main() {
    val names = mutableSetOf("Ava", "Liam")
    val phones = mutableMapOf("Ava" to "5551", "Liam" to "5552")
    println(names)
    println(phones)
}

Expected output

[Ava, Liam]
{Ava=5551, Liam=5552}

Practice Look up a number with get

Create a mutableMapOf("Ava" to "5551", "Liam" to "5552") and print Ava's number with println(phones.get("Ava")).

Starter code

Main.kt
fun main() {
    val phones = mutableMapOf("Ava" to "5551", "Liam" to "5552")
    // Get "Ava"'s number with get and print it
}

Sample solution

Main.kt
fun main() {
    val phones = mutableMapOf("Ava" to "5551", "Liam" to "5552")
    println(phones.get("Ava"))
}

Expected output

5551

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which pair suits a phone book?

  • mutableSetOf<String> + mutableMapOf<String, String> Correct answer
  • listOf + listOf
  • setOf + setOf
  • mutableListOf + mutableMapOf (only list)

Explanation: Set keeps unique names, map holds number lookup.

2 Fill in the blank: add a pair to the book

Question
phones.____("Nora", "5553")
Answer
phones.put("Nora", "5553")

Explanation: phones.put("Nora", "5553") adds a new person to the book.

All lessons in Beginner