Map Class

A Scala Map is a collection of key/value pairs, where the keys must be unique.

Notes:

  • There are immutable and mutable versions; immutable is the default.
  • There are different types of Maps for different needs (sorted Maps, etc.).

This video demonstrates the the default, immutable Map.

Examples

Scala Map examples using my CRUD approach:

// CREATE
val states = Map(
    "AL" -> "Alabama",
    "AK" -> "Alaska",
)

// READ
states("AL")
states("foo")                         // java.util.NoSuchElementException:
                                      //      key not found: foo
states.get("AL")                      // Option[String] = Some(Alabama)
states.getOrElse("AX", "not found")   // "not found"

// READ with for-expression (note that `(k, v)` is a tuple)
val ucMap = for
    (k, v) <- states
yield
    (k, v.toUpperCase)

// UPDATE
val states2 = states + ("CO" -> "Colorado")
val states3 = states2 ++ Map(
    "AR" -> "Arkansas",
    "AZ" -> "Arizona"
)

// DELETE (by key)
val states4 = states3 - "AL"
val states5 = states4 -- Seq("AZ", "AR")

// map method with Map data type
val states6 = states5.map( (k, v) => (k, v.toUpperCase) )

Other Map resources