×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Maps in Scala

By IncludeHelp Last updated : November 15, 2024

Scala maps

A map is a collection that stores its elements as key-value pairs, like a dictionary. Also, known as hash tables, maps have unique keys that are used to retrieve the value related to the key.

Maps can be of two kinds:

Mutable and immutable, for immutable variables the objects can't be changed in the program after initialization. By default the maps are immutable, to use the mutable maps you have to use scala.collection.mutable.Map class.

Creating a Scala Map

There are different syntax to define mutable and immutable Scala maps,

Syntax

Syntax for creating immutable maps:

map_name = Map(key_1 -> value_1, key_2 -> value_2, key_3 -> value_3)

Syntax

Syntax for creating mutable maps:

map_name = Scala.collection.mutable.Map
  (key_1 -> value_1, key_2 -> value_2, key_3 -> value_3)

For a map in Scala, there are three basic operations on Scala maps:

  1. keys: returns an iterable for all keys of the map. Syntax: map_name.keys
  2. values: return an iterable of all values of the map. Syntax: map_name.values
  3. isEmpty: returns true if the map is empty otherwise false.

Some other important methods that are applied on map...

Creating an empty map

Scala programming language allows you to create an empty map that does not contain any value pair. As per user requirements, new elements can be added to it.

Syntax

var map_name = scala.collection.mutable.Map[datatype1 , datatype2]()

Example

object MyClass {
      def main(args: Array[String]): Unit = {
         var map = scala.collection.mutable.Map[Int, String]()
         println("The map created = "+map)
      }
   }

Output

The map created = Map()

Adding value to an array

In Scala maps, there is an option to add new key-value pairs. += operator is used to add new values to the array.

Syntax

var map_name += (key1 , value1)

Example

object MyClass {
      def main(args: Array[String]): Unit = {
         var map = scala.collection.mutable.Map[Int, String]()
         map += (1->"Akash")
         map += (2->"Ram", 3->"Kiran") // adding multiple values.
         println("The map created = "+map)
      }
   }

Output

The map created = Map(2 -> Ram, 1 -> Akash, 3 -> Kiran)

Changing value of Scala maps

By default, the values of Scala maps cannot be changed as it is by default immutable. But you can change values of mutable Scala maps. Using their key and assigning the new value.

Syntax

map_name.(key) = value

Example

object MyClass {
      def main(args: Array[String]): Unit = {
         var map = scala.collection.mutable.Map[Int, String]()
         map += (1->"Akash")
         // adding multiple values.
         map += (2->"Ram", 3->"Kiran") 
         println("The map created = "+map)
         map(2) = "Raju"
         println("The map after updating values = "+map)
      }
   }

Output

The map created = Map(2 -> Ram, 1 -> Akash, 3 -> Kiran)
The map after updating values = Map(2 -> Raju, 1 -> Akash, 3 -> Kiran)

Accessing any specific value of the map

Any value of the Scala map can be accessed using its corresponding key.

Syntax

map_name.(key)

Print all key-value of the map (iterator of the map)

In Scala, the user can iterate over all element of maps using a loop statement. To iterate over a map you can use foreach loop that is specially designed to handle data in structures like an array, list, map.

Syntax

map_name.keys.foreach{=> i
  //values can be extracted using map_name(key) method. 
}

Example

object MyClass {
      def main(args: Array[String]): Unit = {
         var map = scala.collection.mutable.Map[Int, String](1->"Akash" , 2->"Ram", 3->"Kiran" )
        map.keys.foreach{ i =>
         println("Keys :"+i+" Value :"+map(i));
        }
      }
   }

Output

Keys :2 Value :Ram
Keys :1 Value :Akash
Keys :3 Value :Kiran

Deleting value in Scala maps

You can delete values in the map that are not required anymore. The -= operator in Scala map deals with the deletion of values from Map.

Syntax

Map_name -= (key)

Example

object MyClass {
      def main(args: Array[String]): Unit = {
         var map = scala.collection.mutable.Map[Int, String](1->"Akash" , 2->"Ram", 3->"Kiran" )
        println("Intial map =\n"+map)
        map -= (1)
        println("Map after deletion =\n"+map)
      }
   }

Output

Intial map =
Map(2 -> Ram, 1 -> Akash, 3 -> Kiran)
Map after deletion =
Map(2 -> Ram, 3 -> Kiran)

Check if a key is in the map or not

There is an option for the user to check for the value’s availability i.e. whether the value is in the map or not. The Scala contains() method deals with this.

Syntax

map_name.cotains(key)

If the map contains the key, the function will return true otherwise false.

Example

object MyClass {
    def main(args: Array[String]): Unit = {
        var map = scala.collection.mutable.Map[Int, String](1->"Akash" , 2->"Ram", 3->"Kiran" )
        
        if(map.contains(1)){
            println("value "+map(1)+" exists in the map")
        }
        else {
            println("value does nor exist")
        }
        
        println("\nFor second value :\n")
        if(map.contains(5)){
            println("value "+map(5)+" exists in the map")
        }
        else {
            println("value does nor exist")
        }
    }
}

Output

value Akash exists in the map

For second value :

value does nor exist

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.