CodeBlanks Logo Icon CodeBlanks

Map operations

Learn map management with put, get and remove.

Map operations: put, get, remove

On a mutable map put(k, v) adds a new pair or updates an existing key. get(k) returns the value as V?; if the key is missing it returns null. remove(k) takes the key out.

val ages = mutableMapOf("Ava" to 25)
ages.put("Liam", 30)
ages["Nora"] = 28
ages.get("Ava")   // 25
ages.get("missing")  // null

The ages[k] = v syntax does the same job as put; it is just shorter to write.

getOrElse and getOrDefault

Sometimes you want a default value instead of null when a key is missing. getOrElse(k) { default } produces the default with a lambda; getOrDefault(k, default) returns a fixed value.

val ages = mapOf("Ava" to 25)
ages.getOrElse("missing") { 0 }    // 0
ages.getOrDefault("missing", 0)    // 0

These helpers fold the later null check into one line and make the code more readable.

Practice Put a pair and print a value

Start with mutableMapOf("Ava" to 25, "Liam" to 30). Add a new pair with put("Nora", 28), then print Ava's age with println(ages.get("Ava")).

Starter code

Main.kt
fun main() {
    val ages = mutableMapOf("Ava" to 25, "Liam" to 30)
    // Add "Nora" 28 (put), get "Ava"'s age and print it
}

Sample solution

Main.kt
fun main() {
    val ages = mutableMapOf("Ava" to 25, "Liam" to 30)
    ages.put("Nora", 28)
    println(ages.get("Ava"))
}

Expected output

25

Questions and answers

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

1 What does map.get("missing") return?

  • -1
  • null Correct answer
  • Throws an exception
  • Unit

Explanation: On a map, get returns null when the key is missing; no exception.

2 Match method to purpose

Term Meaning
put(k, v) Add/update a key-value pair
get(k) V? (may be null)
remove(k) Remove a key
keys All keys

3 Fill in the blank: put a pair

Question
ages.____("Nora", 28)
Answer
ages.put("Nora", 28)

Explanation: ages.put("Nora", 28) adds or updates the pair.

All lessons in Beginner