Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly.
Maps can be created in different ways based upon our requirement and nature of the Map. We have different syntax depending upon whether the Map is mutable or immutable.
// Immutable variable = Map(key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....) // Mutable variable = scala.collection.mutable.Map(key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....)
There are three basic operations we can carry out on a Map:
- keys: In Scala Map, This method returns an iterable containing each key in the map.
- values: Value method returns an iterable containing each value in the Scala map.
- isEmpty: This Scala map method returns true if the map is empty otherwise this returns false.
Values can be accessed using Map variable name and key.
If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map. Therefore, it is recommended to use contains() function while accessing any value using key.
This function checks for the key in the Map. If the key is present then it returns true, false otherwise.
If we try to update value of an immutable Map, Scala outputs an error. On the other hand, any changes made in value of any key in case of mutable Maps is accepted.
Updating immutable Map:
error: value update is not a member of scala.collection.immutable.Map[String, Int]
Updating mutable Map:
Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)
After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20)
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
Before Adding: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)
After Adding: Map(Ajay -> 10, Dinesh -> 60, Charlie -> 50, Bhavesh -> 20)
Deleting a key-value pair is similar to adding a new entry. The difference is instead of += we use -= operator followed by keys that are to be deleted.
Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)
After Deleting: Map(Bhavesh -> 20)
Key-value pair corresponds to a tuple with two elements. Therefore, while performing iteration loop variable needs to be a pair.
To understand syntax and working of loops in Scala refer : Loops|Scala
Key:Ajay, Value:30 Key:Charlie, Value:50 Key:Bhavesh, Value:20
In Scala Map, We can also create an empty Map and later add elements to it.
Empty Map: Map() New Entry: Map(Charlie -> 50)