Scala Maps

By: Stephen Patrick | 09 Aug 2016 | Category: Scala Language Basics

Related Contents

Scala Maps

As we mentioned previously Scala provides a number of collection classes. The collection classes that Scala provides can be divided into mutable and immutable types. Scala also provides a Map data type. Moreover, Scala provides both mutable and immutable Map types. Both the immutable and mutable types have the same simple name. However, they are modeled in separate class hierarchies.

Both the mutable and immutable Maps extend the scala.collection.Map trait. Then the hierarchy splits into a mutable and immutable set of traits: scala.collection.mutable.Map and scala.collection.immutable.Map respectively. The concrete Map implementations extend these traits: scala.collection.mutable.HashMap and scala.collection.immutable.HashMap.

Scala Creating A Map

We can create a map in Scala using some syntactic sugar. Scala will infer the types for the key and value as Int and String.

val alphaMap= Map( 1 -> "a", 2 -> "b" )

However, since we did not explicitly use an import Scala creates an immutable Map.

To create a mutable Map we need to be more explicit.

import scala.collection.mutable.Map
val alphaMap = Map[Int, String]()
alphaMap+= (1 -> "a")

Scala Get Map Value

To retrieve a value from a Map is very simple we can use the key to lookup the value.


However, if the value does not exist it will result in a java.util.NoSuchElementException



java.util.NoSuchElementException: key not found: 3

To avoid such problems we can use the safer get method which will return an object of type Option. The Option type wraps a value as an Object which can return an object of type None or an object of Some(value).



Option[String] = None
Option[String] = Some(a)

Scala Pattern Matching

We can use pattern matching to process the returned Option value. This allows us to easily handle the return value without having to worry if an exception was thrown.

val char = alphaMap.get(3)

val result = char match {
   case None => "Char Not Found"
   case Some(value) => "Found "+value+""


String = Char Not Found

Scala Transform A Collection Into A Map

The groupBy method can be used to transform a collection into a Map.

class Field(val name:String, val fieldType:String)
var fieldList = List(new Field("name", "String"),  new Field("amount", "Double"))
var fieldMap = fieldList.groupBy(