← Back to Scala Course | Chapter 6: Collections Basics | Lesson 6 of 8

Map

In this page:

  1. Map

Map

A Map stores key-value pairs and gives fast lookup by key, created with Map("a" -> 1, "b" -> 2) using the -> arrow syntax. Map(...) is immutable by default, and keys must be unique. Accessing a missing key with map(key) throws, so .get(key) (returning an Option) or .getOrElse are the safer alternatives.

Warning: Accessing a missing key with map(key) throws a NoSuchElementException -- use .get(key) or .getOrElse(key, default) for safety.

Example: Map

markup
object Main extends App {
  val ages = Map("Alice" -> 30, "Bob" -> 25)

  println(ages("Alice"))
  println(ages.getOrElse("Cara", -1))

  for ((name, age) <- ages) {
    println(s"$name is $age")
  }
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.