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.
How to create Scala Maps
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.
Syntax :
// 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, ....)
Operations on a Scala Map
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.
Accessing Values Using Keys
Values can be accessed using Map variable name and key.
Example:
object GFG
{
def main(args : Array[String])
{
val mapIm = Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
val ajay = mapIm( "Ajay" )
println(ajay)
}
}
|
Output:
30
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.
object GFG
{
def main(args : Array[String])
{
val mapIm = Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
val ajay = if (mapIm.contains( "Ajay" ))
mapIm( "Ajay" ) else 0
val john = if (mapIm.contains( "John" ))
mapIm( "John" ) else 0
println( "Ajay:" + ajay)
println( "John:" + john)
}
}
|
Output:
Ajay:30
John:0
Updating the values
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.
Example:
Updating immutable Map:
object GFG
{
def main(args : Array[String])
{
val mapIm = Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
println(mapIm)
mapIm( "Ajay" ) = 10
println(mapIm)
}
}
|
Output:
error: value update is not a member of scala.collection.immutable.Map[String, Int]
Updating mutable Map:
object GFG
{
def main(args : Array[String])
{
val mapMut = scala.collection.mutable.Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
println( "Before Updating: " + mapMut)
mapMut( "Ajay" ) = 10
println( "After Updating: " + mapMut)
}
}
|
Output:
Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)
After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20)
Adding new key-value pair
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
Example:
object GFG
{
def main(args : Array[String])
{
val mapMut = scala.collection.mutable.Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
println( "Before Adding: " +mapMut)
mapMut + = ( "Ajay" - > 10 , "Dinesh" - > 60 )
println( "After Adding: " +mapMut)
}
}
|
Output:
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:
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.
Example:
object GFG
{
def main(args : Array[String])
{
val mapMut = scala.collection.mutable.Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
println( "Before Deleting: " +mapMut)
mapMut - = ( "Ajay" , "Charlie" )
println( "After Deleting: " + mapMut)
}
}
|
Output:
Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)
After Deleting: Map(Bhavesh -> 20)
Iteration in a Map
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
Example:
object GFG
{
def main(args : Array[String])
{
val mapMut = scala.collection.mutable.Map( "Ajay" - > 30 ,
"Bhavesh" - > 20 ,
"Charlie" - > 50 )
for ((k, v) < - mapMut)
{
print( "Key:" +k+ ", " )
println( "Value:" +v)
}
}
}
|
Output:
Key:Ajay, Value:30
Key:Charlie, Value:50
Key:Bhavesh, Value:20
Empty Map
In Scala Map, We can also create an empty Map and later add elements to it.
Example:
object GFG
{
def main(args : Array[String])
{
val mapMut = scala.collection.mutable.Map[String, Int]()
println( "Empty Map: " + mapMut)
mapMut + = ( "Charlie" - > 50 )
println( "New Entry: " + mapMut)
}
}
|
Output:
Empty Map: Map()
New Entry: Map(Charlie -> 50)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Feb, 2019
Like Article
Save Article