A map represents an mapping from keys to values.

The Scala Map type has two type parameters, for the key type and for the value type. So a Map[String, Int] maps strings to integers, while a Map[Int, Set[String]] maps integers to sets of strings.

Scala provides both immutable and mutable maps. By default, Map is equal to scala.collection.immutable.Map.

You can create maps by listing the mappings. Here the -> operator is convenient: It simply creates a pair out of two objects.

scala> val m = Map("A" -> 7, "B" -> 13)
m: scala.collection.immutable.Map[java.lang.String,Int] = Map(A -> 7, B -> 13)

With a map, we can very efficiently look up the value for a given key. This raises an exception if the key is not in the map:

scala> m("A")
res0: Int = 7
scala> m("C")
java.util.NoSuchElementException: key not found: C

To avoid the exception, we can first check if the key is in the map using contains, or use the getOrElse method, which uses a default value instead of throwing an exception:

scala> m contains "A"
res1: Boolean = true
scala> m contains "C"
res2: Boolean = false
scala> m.getOrElse("A", 99)
res3: Int = 7
scala> m.getOrElse("C", 99)
res4: Int = 99

The + and - operators can be used to add mappings, update mappings, or remove mappings. The operators return a new map, and leave the original map unchanged:

scala> val m1 = m + ("C" -> 37)
m1: scala.collection.immutable.Map[java.lang.String,Int] = Map(A -> 7, B -> 13, C -> 37)
scala> println(m)
Map(A -> 7, B -> 13)
scala> println(m1)
Map(A -> 7, B -> 13, C -> 37)
scala> println(m + ("A" -> 99))
Map(A -> 99, B -> 13)
scala> println(m - "A")
Map(B -> 13)
scala> println(m - "C")
Map(A -> 7, B -> 13)

A map can be converted to a set, list, or array of pairs:

scala> m.toSet
res5: scala.collection.immutable.Set[(java.lang.String, Int)] = Set((A,7), (B,13))
scala> m.toArray
res6: Array[(java.lang.String, Int)] = Array((A,7), (B,13))
scala> m.toList
res7: List[(java.lang.String, Int)] = List((A,7), (B,13))

Mutable maps

scala.collection.mutable.Map provides mutable maps. In addition to the methods above, mutable sets provide += and -= operators:

For mutable maps, mappings can be defined and updated using the parenthesis syntax:

scala> val m = scala.collection.mutable.Map[String,Int]()
m: scala.collection.mutable.Map[String,Int] = Map()
scala> m("A") = 7
scala> m("B") = 13
scala> m("A")
res3: Int = 7
scala> m("A") = 99
scala> m("A")
res5: Int = 99