Maps in Scala

Maps are Scala’s built-in associative data type (usually called hashes or dicts in other languages).

To create an empty map, use the Map class constructor:

import scala.collection.mutable.Map

object Example extends App {
    val m = Map[String, Int]()
    
    // Set key/value pairs using typical syntax.
    m("k1") = 7
    m("k2") = 13

    // Printing a map will show all of its key/value pairs.
    println("map: " + m)

    // Get a value for a key.
    val v1 = m("k1")
    println("v1: " + v1)

    // If the key doesn’t exist, a NoSuchElementException is thrown unless handled.
    val v3 = m.getOrElse("k3", 0)
    println("v3: " + v3)

    // Get the number of key/value pairs in the map.
    println("len: " + m.size)

    // Remove key/value pairs from a map.
    m -= "k2"
    println("map: " + m)

    // To remove all key/value pairs from a map, use clear().
    m.clear()
    println("map: " + m)

    // Optional second return value to check if a key was present in the map.
    val prs = m.contains("k2")
    println("prs: " + prs)

    // Declare and initialize a new map.
    val n = Map("foo" -> 1, "bar" -> 2)
    println("map: " + n)

    // Check if two maps are equal.
    val n2 = Map("foo" -> 1, "bar" -> 2)
    if (n == n2) {
        println("n == n2")
    }
}

To run the program, save the code in a file named maps.scala and use scala to execute it.

$ scala maps.scala
map: Map(k1 -> 7, k2 -> 13)
v1: 7
v3: 0
len: 2
map: Map(k1 -> 7)
map: Map()
prs: false
map: Map(foo -> 1, bar -> 2)
n == n2

Note that maps appear in the form Map(k -> v, k -> v) when printed with println.