Home » Scala language

Maps in Scala

Scala Maps: Map data structure stores values as a key-value pair. In this Scala tutorial on maps, we will learn the basics of maps and some important functions on maps.
Submitted by Shivang Yadav, on July 25, 2019

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 for Creating Immutable maps:

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

Syntax for Creating mutable maps:

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

Operations on Map

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...

1) 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]) {
         var map = scala.collection.mutable.Map[Int, String]()
         println("The map created = "+map)
      }
   }

Output

The map created = Map()

2) 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]) {
         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)

3) 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]) {
         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)

4) Accessing any specific value of the map

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

Syntax:

map_name.(key)

5) 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]) {
         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

6) 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]) {
         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)

7) 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]) {
        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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.