Start learning free

LESSON 131 OF 677 · DICTIONARIES

Deleting a Key from a Scala Map

Lesson Read the full explanation

TL ; DR:

A mutable Map's remove method takes a key. It deletes that key and its value.


val toys = scala.collection.mutable.Map("ball" -> 3, "doll" -> 2, "kite" -> 1)
toys.remove("kite")

println(toys.size)   // 2


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call remove on the map with the key. The key and its value go away together.

The size drops by 1. The key is gone, so toys.contains("kite") is now false.

remove also returns the deleted value inside an Option. Here that's Some(1). For a missing key it returns None, and nothing changes.

Only a mutable map can lose keys. That's why toys is a scala.collection.mutable.Map.

Watch out: after the delete, toys("kite") throws a NoSuchElementException. Check with contains first.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.size again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · DICTIONARIES

    Deleting Dictionary Keys in Scala, explained

    Removing an entry

    Sometimes an entry has to go: a shop stops selling an item, a player leaves a game. On a mutable map, remove(key) deletes the key and its value together.

    val animals = scala.collection.mutable.Map("cat" -> 4, "dog" -> 2, "rabbit" -> 1)
    animals.remove("rabbit")
    println(animals.size)   // 2
    

    The size drops by 1, and animals.contains("rabbit") is now false.

    What remove returns

    remove hands back the deleted value inside an Option. For "rabbit" that is Some(1). If the key isn't in the map, it returns None and nothing changes, so removing a key twice is harmless. You can ignore the result, as the lesson's task does.

    val gone = animals.remove("rabbit")
    println(gone)                      // Some(1)
    println(animals.remove("rabbit"))  // None
    

    There is also the operator form animals -= "dog", which removes by key too and returns the map.

    Only a mutable map can lose keys

    The default Map in Scala is immutable. It has no remove method that changes it, which is why the lesson builds animals with scala.collection.mutable.Map. If you need a map that drops keys over time, create a mutable one.

    After the delete

    Once the key is gone, reading it with animals("rabbit") throws NoSuchElementException: key not found: rabbit. Check with contains first, or read with getOrElse.

    An immutable map does have removed(key), but it doesn't change the map. It returns a new map without the key and leaves the original as it was. That is a different style of working, so this lesson keeps to the mutable map, where remove changes the map you already have.

    Delete or zero?

    Setting a count to 0 is not the same as deleting. With animals("rabbit") = 0, the key stays: the size is still 3 and contains("rabbit") is still true. Choose deletion when "none left" should mean "not listed".

    The task

    A pet shop counts what it has for sale in animals: each key is a kind of animal, each value is how many the shop has. The last rabbit just went home. The task deletes the key "rabbit", then prints animals.size again. The code at the bottom checks whether any rabbits are left.

    1. Below the first println, call animals.remove("rabbit").
    2. Print animals.size again. One key is gone, so the number drops from 3 to 2.
    val animals = scala.collection.mutable.Map("cat" -> 4, "dog" -> 2, "rabbit" -> 1)
    println(animals.size)
    animals.remove("rabbit")
    println(animals.size)
    if (animals.contains("rabbit")) {
        println("We still have rabbits")
    } else {
        println("No rabbits left")
    }
    

    It prints:

    3
    2
    No rabbits left
    

    In the task, the number printed after the delete confirms the change: 3 entries before, 2 after. The final check then takes the else branch, because contains("rabbit") is now false.

    Common mistakes

    • Setting the count to 0 instead. animals("rabbit") = 0 keeps the key. The size stays 3 and contains("rabbit") stays true.
    • Passing a value. remove takes a key, not a count. For this map the keys are strings, so animals.remove(1) is a type error: the compiler found an Int where a String is required.
    • Using an immutable map. A map made with plain Map(...) can't be changed in place. Calling remove on it fails to compile with value remove is not a member of Map[String, Int]; use the mutable one.

    Key takeaways

    • remove(key) deletes a key and its value from a mutable map.
    • It returns the old value as an Option (Some or None), and a missing key is not an error.
    • After removal, contains is false and size is one less.
    Keep going with Scala500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free