Skip to main content

How to work with Maps in Scala

For scala 2.12.x

Maps are very useful data structures. They allow you to retrieve a value by using a key.

In this example, as we want to reuse the same map, we have declared it as var. This conde won't work with a val because the (+) and (-) operations return a new Map with the result of the operation.

Creating an empty map

var a: Map[String, String] = Map[String, String].empty()

Adding values

// Add just one element
a = a + ("Key 2" -> "Value 2")

// Add Multiple elements
a = a + ("Key 3" -> "Value 3", "Key 4" -> "Value 4")

In scala 2.13+ the "concat (++)" method of the Map replaces this (+) approach.

Replacing values

Just add an existing key with a new value.

//Replace element
a = a + ("Key 3" -> "New value 3")

Removing values

// Remove element
a = a - "Key 3"

Source

https://www.scala-lang.org/api/2.12.x/scala/collection/mutable/Map.html