🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Maps

A map is a collection that stores pairs of keys and values. Each key appears once, and the value paired with a key is found by using that key.

A lookup reads the value paired with a key

Pairs are written with an arrow between the key and the value. Placing a key in round brackets reads its value.

@main def main(): Unit =
  val ages = Map("Ana" -> 30, "Bo" -> 25)
  println(ages("Ana"))
  println(ages("Bo"))

getOrElse gives a fallback for a missing key

A plain lookup fails when the key is missing. getOrElse returns a fallback value instead, and contains checks a key first.

@main def main(): Unit =
  val ages = Map("Ana" -> 30, "Bo" -> 25)
  println(ages.getOrElse("Ana", 0))
  println(ages.getOrElse("Cy", 0))
  println(ages.contains("Cy"))

Size counts pairs and sorted keys list every key

The size counts the pairs in a map. Sorting the keys into a list gives a safe order to print.

@main def main(): Unit =
  val ages = Map("Cy" -> 41, "Ana" -> 30, "Bo" -> 25)
  println(ages.size)
  println(ages.keys.toList.sorted)

Example

@main def main(): Unit =
  val prices = Map("pen" -> 2, "book" -> 5, "bag" -> 12)
  println(prices("book"))
  println(prices.getOrElse("hat", 0))
  println(prices.size)
  println(prices.keys.toList.sorted)

Key points

  • Creation: Map("a" -> 1) creates a map where the key "a" is paired with the value 1.
  • Lookup: m("a") gives the value paired with the key "a".
  • Safe lookup: m.getOrElse("a", 0) gives the paired value, or 0 when the key is missing.
  • Checking: m.contains("a") gives true when the key "a" is in the map.
  • Size: m.size gives how many pairs the map holds.
  • Keys: m.keys.toList.sorted returns all the keys as a sorted list.

In this example, the program creates a map of three prices and looks up the price of a book, which is 5. It asks for the missing key hat with getOrElse and receives the fallback 0, then prints the size and the sorted list of keys.

Note

A map does not promise an order for its pairs, so this course never prints a map directly.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does Map("pen" -> 2).getOrElse("hat", 9) give?