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

Map

A Map links keys to values, like a phone book where a name leads you to a number. You look up a key and get its value quickly.

In this page:

  1. Map
Syntax
scala
val map = Map(key1 -> value1, key2 -> value2)
map(key)
map.get(key)
val updated = map + (key3 -> value3)

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")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using ages("Cara") for a missing key, which throws NoSuchElementException; use getOrElse or get.
  2. Writing Map("a": 1) with a colon, when the pairs use ->.
  3. Expecting ages + ("Dan" -> 20) to modify ages, when the default Map is immutable and returns a new map.
🔒

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.