How to iterate Map in Scala?

Here, we will learn methods to iterate maps in Scala. There are multiple methods to iterate/traverse maps and we will learn them with examples and syntaxes.
Submitted by Shivang Yadav, on May 12, 2020

Iterating/ traversing Maps is the process of accessing all elements of the map. For this, we will loop over all elements of the map and print the key-value pairs of the elements of the map.

A map is a data structure that contains data elements in the form of key-value pairs and an element can be accessed using the key.

Syntax for creating map:

    val map_element = Map( key1 -> value1 , key2 -> value2 ) 

Sample Map:

    val programmingLang = Map(1 -> "C", 2 -> "C++", 3 -> "Scala"); 

Iterating over Map

You can iterate over a map and excess its elements in multiple ways:

  1. Using for loop
  2. Using foreach Loop
  3. Using iterator method

1) Iterating over the map in Scala using the for loop

The for loop is used to loop over elements of the map.

Syntax:

    for((key,value) <- map_name){
        //code to be executed 
    }

Program to print elements of a map using for loop

object MyObject {
    def main(args: Array[String]) {
        val progLang = Map(1 -> "C" , 2 -> "C++" , 3 -> "Scala" , 4 -> "Python")
        
        println("Iterating over Map using for Loop")
        for((count,language) <- progLang){
            println(count + " -> " + language)
        }
    }
}

Output

Iterating over Map using for Loop
1 -> C
2 -> C++
3 -> Scala
4 -> Python

Explanation:

In this program, we have illustrated the use of for loop for iterating over a map. We have created a map named progLang and then using the for loop we have to print the key and value of the map.

2) Iterating over the map in Scala using the foreach loop

The foreach loop is called using the map name and it iterates over all the elements of the map.

Syntax:

    map_name.foreach{
        //code to be executed 
    }

There can be two different methods to use the foreach loop for accessing the elements of the map. They match expression and tuple based access.

In match expression based accessing we will be accessing the elements of the map are named and accessed suing it.

Syntax:

    Map_name.foreach{
        case(key, value) => //Code for accessing the values...
    }

The other method is quite each as it uses a tuple to access elements of the map. So, the key will be the first value of tuple, and value will be the second value of the tuple.

Syntax:

    Map_name.foreach( x => //code for accessing the values...

Program to print elements of a map using foreach loop

object MyObject {
    def main(args: Array[String]) {
        val myBikes = Map(1 -> "ThunderBird350" , 2 -> "Yamaha R3" , 3 -> "Iron 883" , 4 -> "BMW S1000RR")

        println("Iterating over Map using foreach Loop")
        myBikes.foreach(bike => println("Bike No. : " + bike._1 + " name : " + bike._2))
    }
}

Output

Iterating over Map using foreach Loop
Bike No. : 1 name : ThunderBird350
Bike No. : 2 name : Yamaha R3
Bike No. : 3 name : Iron 883
Bike No. : 4 name : BMW S1000RR

Explanation:

In this program, we have illustrated the use of foreach loop for iterating over a map. We have created a map named myBikes and then used the foreach to iterate over it, using the tuple access method.

3) Iterating over the map in Scala using the iterator method

The iterator method is used to create an iterator for the map that is used to loop over the values of the map.

Syntax:

    map_name.iterator 

It returns an iterator based on the map. Then we have to use iterator_name.next method to print the elements of the iterator which are returned as tuples in case of the map.

Program to print elements of a map using iterator method

object MyObject {
    def main(args: Array[String]) {
        val myBikes = Map(1 -> "ThunderBird350" , 2 -> "Yamaha R3" , 3 -> "Iron 883" , 4 -> "BMW S1000RR")

        println("Iterating over Map using iterator method")
        val bike = myBikes.iterator
        while(bike.hasNext)
            println(bike.next)
    }
}

Output

Iterating over Map using iterator method
(1,ThunderBird350)
(2,Yamaha R3)
(3,Iron 883)
(4,BMW S1000RR)

Explanation:

In this program, we have illustrated the use of iterator method for iterating over a map. We have created a map and then defined an iterator method that will be used to iterate over the elements of the map. The method itorator.hasnext is used to check if the next element of the iterator is present and the print the element as a tuple using iterator.next method.



Comments and Discussions!

Load comments ↻





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