Scala Maps
Overview of Scala's maps
Maps are collections of key-value pais. Just like arrays, in Scala we can distinguish between mutable and immutable maps. Furthermore, the default map type is a hash map. However, tree maps are also provided [1].
As mentioned above, in Scala, a map is a collection of key-value pairs. A pair is a grouping of two values that do not have necessarily the same type [1]. We have two ways cosntructing a pair
- Using the
->
operator. - Using
(key, value)
constructs
We can construct an immutable Map
as shown below
val map1 = Map("France" -> "Paris", "England" -> "London", "Greece" -> "Athens")
The elements in Map
cannot be changed
map1("Greece") = "New York"
Nevertheless, the following is a way to update an immmutable map
val map2 = map1 + ("Greece" -> "New York")
Similarly, we can remove or add a new element
val map3 = map2 + ("Italy" -> "Rome")
val map4 = map3 - "Greece"
In order to get a mutable map we need to explicitly say so
import scala.collection.mutable.Map
val grades = Map("Alex" -> 10, "Alice" -> 15, "George" ->5)
grades("Alex") = 12
grades
Above we have initialized the map at construction time. However, we might not always be able to do so. In this case, we need to specify explicitly what type of map we want [1]
import scala.collection.mutable.HashMap
val gradesEmpty = new HashMap[String, Int]
If the map is mutable, this means tha we can add, change or remove elements. We can add a new element in two ways
- Use operator
(key)
. If thekey
exists it will update the value corresponding to the key. Otherwise, it will create a new key-value pair - Use operator
+=
followed by a tuple of pairs
gradesEmpty += ("Suzana" -> 15, "John" -> 3)
We can remove a key-value pait using the -=
operator
gradesEmpty -= "Suzana"
How can we find whether a key is contained in a map?
grades.contains("Alex")
grades.contains("")
One nice feature is that we can query a map with a key and specify a default value in case that the key does not exist
grades.getOrElse("Alex", "Invalid Name")
grades.getOrElse("SomeOne", "Invalid Name")
As shown above, we can access the value of a particular key using the ()
operator. This, however, will an exception if the key does not exit. Finally, we can use grades.get( someKey )
. This returns an Option
object that is either Some( value for key )
or None
[1].
- Cay Horstmann,
Scala for the Impatient 1st Edition