Open In App

Scala Map

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:

  1. keys: In Scala Map, This method returns an iterable containing each key in the map.
  2. values: Value method returns an iterable containing each value in the Scala map.
  3. isEmpty: This Scala map method returns true if the map is empty otherwise this returns false.
  4.  

    Accessing Values Using Keys

    Values can be accessed using Map variable name and key.
    Example:




    // Scala map program of 
    // Accessing Values Using Keys
      
    // Creating object 
    object GFG
    {
        // Main method
        def main(args:Array[String])
        {
      
            val mapIm = Map("Ajay" -> 30
                            "Bhavesh" -> 20,
                            "Charlie" -> 50)
      
            // Accessing score of Ajay
            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.




    // Scala map program of 
    // Accessing Values Using 
    // Keys by contains() function
      
    // Creating object
    object GFG
    {
          
        // Main methode
        def main(args:Array[String])
        {
            val mapIm = Map("Ajay" -> 30,
                            "Bhavesh" -> 20,
                            "Charlie" -> 50)
              
            // the key check in the Map
            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:




    // Scala map program of 
    // Updating the values
    // in immutable map
      
    // Creating an object
    object GFG
    {
        // Main method
        def main(args:Array[String])
        {
      
            val mapIm = Map("Ajay" -> 30
                            "Bhavesh" -> 20
                            "Charlie" -> 50)
                  
            println(mapIm)
              
            //Updating
            mapIm("Ajay") = 10 
      
            println(mapIm)
      
        }
    }

    
    

    Output:

    error: value update is not a member of scala.collection.immutable.Map[String, Int]

     
    Updating mutable Map:




    // Scala map program of 
    // Updating the values
    // in mutable map
      
    // Creating Object
    object GFG
    {
          
        // Main method
        def main(args:Array[String])
        {
      
            val mapMut = scala.collection.mutable.Map("Ajay" -> 30,
                                                      "Bhavesh" -> 20
                                                      "Charlie" -> 50)
            println("Before Updating: " + mapMut)
      
            // Updating
            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:




    // Scala map program of 
    // Adding new key-value pair
      
    // Creating object
    object GFG
    {
          
        // Main method
        def main(args:Array[String])
        {
      
            val mapMut = scala.collection.mutable.Map("Ajay" -> 30
                                                      "Bhavesh" -> 20,
                                                      "Charlie" -> 50)
      
            println("Before Adding: "+mapMut)
      
            // Adding a new key "Dinesh" and 
            // updating an existing key "Ajay"
            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:




    // Scala map program of 
    // Deleting new key-value pair
      
    // Creating object
    object GFG
    {
          
        // Main method
        def main(args:Array[String])
        {
      
            val mapMut = scala.collection.mutable.Map("Ajay" -> 30,
                                                      "Bhavesh" -> 20,
                                                      "Charlie" -> 50)
      
            println("Before Deleting: "+mapMut)
      
            // Deleting key-value pairs with
            // keys "Ajay" and "Charlie"
            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:




    // Scala map program of 
    // Iteration in a Map
      
    // Creating object
    object GFG
    {
          
        // Main method
        def main(args:Array[String])
        {
      
            val mapMut = scala.collection.mutable.Map("Ajay" -> 30,
                                                      "Bhavesh" -> 20,
                                                      "Charlie" -> 50)
      
            // (k, v) is a tuple with two elements
            for((k, v) <- mapMut) 
            {    
                //where k is key and v is value
                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:




    // Scala map program of 
    // Empty Map
      
    // Creating object
    object GFG
    {
          
        // Main method
        def main(args:Array[String])
        {
      
            // Creation of Map having key-value
            // pairs of type (String, Int)
            val mapMut = scala.collection.mutable.Map[String, Int]()
      
            println("Empty Map: " + mapMut)
      
            // Adding new entry
            mapMut += ("Charlie" -> 50
      
             println("New Entry: " + mapMut)
        }
    }

    
    

    Output:

    Empty Map: Map()
    New Entry: Map(Charlie -> 50)


    Last Updated : 07 Feb, 2019
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
Similar Reads