TExcelTAD
Home › Scala › Scala Maps

Scala Maps

A Map stores key → value pairs, and looks values up by key. Keys are unique; storing a value under an existing key replaces the old one. The default Map is immutable, so "updating" a map returns a new one.

Creating and reading a map

scala · try it yourself
@main def run(): Unit =
  val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo", "Peru" -> "Lima")
  println(capitals("Japan"))
  println(capitals.get("Peru"))
  println(capitals.get("Chad"))
  println(capitals.getOrElse("Chad", "unknown"))
  println(capitals.contains("France"))
  println(capitals.size)
Tokyo
Some(Lima)
None
unknown
true
3

"France" -> "Paris" is just another way to write the tuple ("France", "Paris").

Note: capitals("Chad") would throw a NoSuchElementException. Prefer get (returns an Option) or getOrElse when a key might be missing.

Adding, updating and removing

scala · try it yourself
@main def run(): Unit =
  val stock = Map("apple" -> 5, "pear" -> 2)
  val more = stock + ("plum" -> 9)
  val changed = more.updated("apple", 7)
  val fewer = changed - "pear"
  val merged = fewer ++ Map("kiwi" -> 1)
  println(more)
  println(changed)
  println(fewer)
  println(merged)
  println(s"stock unchanged: $stock")
Map(apple -> 5, pear -> 2, plum -> 9)
Map(apple -> 7, pear -> 2, plum -> 9)
Map(apple -> 7, plum -> 9)
Map(apple -> 7, plum -> 9, kiwi -> 1)
stock unchanged: Map(apple -> 5, pear -> 2)

Like sets, maps with more than four entries are hash-based and have no defined order. Sort the entries before printing when order matters.

Iterating

scala · try it yourself
@main def run(): Unit =
  val prices = Map("tea" -> 3.5, "coffee" -> 4.2, "juice" -> 5.0)
  for (item, price) <- prices do
    println(f"$item%-7s $price%5.2f")
  println(prices.keys.toList.sorted)
  println(prices.values.sum)
  prices.toList.sortBy(-_._2).foreach((k, v) => println(s"$k: $v"))
tea      3.50
coffee   4.20
juice    5.00
List(coffee, juice, tea)
12.7
juice: 5.0
coffee: 4.2
tea: 3.5

Transforming maps

Method Result
m.map((k, v) => (k, f(v))) a new map with transformed pairs
m.view.mapValues(f).toMap only values transformed
m.filter((k, v) => …) entries that pass the test
m.keySet, m.values keys as a Set, values as an Iterable
m.toList List[(K, V)]
m.groupBy(...), xs.groupMapReduce(...) build maps from collections
scala · try it yourself
@main def run(): Unit =
  val celsius = Map("Oslo" -> 4.0, "Cairo" -> 31.0, "Lima" -> 19.0)
  val fahrenheit = celsius.map((city, c) => (city, c * 9 / 5 + 32))
  println(fahrenheit)
  val warm = celsius.filter((_, c) => c > 15)
  println(warm.keySet)
  println(celsius.view.mapValues(_.round).toMap)
Map(Oslo -> 39.2, Cairo -> 87.8, Lima -> 66.2)
Set(Cairo, Lima)
Map(Oslo -> 4, Cairo -> 31, Lima -> 19)

Counting with maps

Counting things is one of the most common uses of a map.

scala · try it yourself
@main def run(): Unit =
  val words = "the cat and the dog and the bird".split(" ").toList
  val counts = words.groupMapReduce(identity)(_ => 1)(_ + _)
  counts.toList.sortBy((w, n) => (-n, w)).foreach((w, n) => println(s"$w: $n"))

  val withDefault = Map("a" -> 1).withDefaultValue(0)
  println(withDefault("zzz"))
the: 3
and: 2
bird: 1
cat: 1
dog: 1
0

groupMapReduce(key)(value)(combine) groups the words, maps each to 1, and adds the ones up per word.

SortedMap and mutable maps

scala
import scala.collection.immutable.SortedMap
SortedMap("b" -> 2, "a" -> 1)          // TreeMap(a -> 1, b -> 2), always ordered by key

import scala.collection.mutable
val cache = mutable.Map[String, Int]()
cache("x") = 10                        // update in place
cache.getOrElseUpdate("y", 20)         // insert if missing

Test yourself

What does Map("a" -> 1).get("b") return?

  1. 0
  2. null
  3. None
  4. It throws

What happens when you add a pair whose key already exists?

  1. Both values are kept
  2. The new value replaces the old one in the returned map
  3. An exception is thrown
  4. The old value is kept

Which expression is the same as the tuple ("k", 1)?

  1. "k" :: 1
  2. "k" -> 1
  3. "k" => 1
  4. "k" <- 1