Scala maps are like dictionaries; a combination of key-value pairs. By definition, key-value pairs are uniquely identified in the map. Any key can be directly used to access a value. It is important for keys to be unique, but values do not need to be unique.
In Scala, there are two kinds of maps: Mutable and Immutable. A mutable map object’s value can be changed, while immutable maps do not allow the values associated with keys to be changed.
Scala uses immutable maps by default. You can import
scala.collection.mutable.Map
to use mutable maps.
The following is the syntax to declare a map in Scala.
// Method 1
// Empty hash table whose keys are strings and values are integers:
val people: Map[String,Int] = Map()
// Method 2
// A map with keys and values.
val people = Map("Michael" -> 25, "Ross" -> 27, "Ali" -> 21)
In the following code, we explore maps in Scala. Specifically, we look at the commonly used methods of maps:
keys
: used to access all the keys inside the mapvalues
: used to access all the values inside the map++
: used to combine two maps into oneisEmpty
: used to check whether the map is empty or not, returning a boolean valueobject Main extends App {val people = Map("Michael" -> "25","Ross" -> "27","Ali" -> "21")// check if map is emptyprintln("Is the Map empty? ", people.isEmpty)println( "Keys : " + people.keys )println( "Values : ")people.values.foreach(println)// Iterating each key-value pairpeople.keys.foreach{ i =>print( "Key = " + i )println(", Value = " + people(i))}// We can also access indivdual values based on keys.println(people("Michael"))// one can join two maps using ++ operatorprintln("Joining two maps together")val people1 = Map("Andrew" -> "33","Indiana" -> "54","Peter" -> "12")val people2 = people ++ people1people2.keys.foreach{ i =>print( "Key = " + i )println(", Value = " + people2(i))}}
Free Resources