Scala Language Collections Map Collection Cheatsheet


Example

Note that this deals with the creation of a collection of type Map, which is distinct from the map method.

Map Creation

Map[String, Int]() 
val m1: Map[String, Int] = Map()
val m2: String Map Int = Map()

A map can be considered a collection of tuples for most operations, where the first element is the key and the second is the value.

val l = List(("a", 1), ("b", 2), ("c", 3))
val m = l.toMap                               // Map(a -> 1, b -> 2, c -> 3)

Get element

val m = Map("a" -> 1, "b" -> 2, "c" -> 3)

m.get("a")  // Some(1)
m.get("d")  // None
m("a")      // 1
m("d")      // java.util.NoSuchElementException: key not found: d

m.keys      // Set(a, b, c)
m.values    // MapLike(1, 2, 3)

Add element(s)

Map("a" -> 1, "b" -> 2) + ("c" -> 3)               // Map(a -> 1, b -> 2, c -> 3)
Map("a" -> 1, "b" -> 2) + ("a" -> 3)               // Map(a -> 3, b -> 2)
Map("a" -> 1, "b" -> 2) ++ Map("b" -> 3, "c" -> 4) // Map(a -> 1, b -> 3, c -> 4)

Common operations

In operations where an iteration over a map occurs (map, find, forEach, etc), the elements of the collection are tuples. The function parameter can either use the tuple accessors (_1, _2), or a partial function with a case block:

m.find(_._1 == "a")  // Some((a,1))
m.map {
  case (key, value) => (value, key)
}                    // Map(1 -> a, 2 -> b, 3 -> c)
m.filter(_._2 == 2)  // Map(b -> 2)
m.foldLeft(0){
  case (acc, (key, value: Int)) => acc + value
}                    // 6