2 ways to iterate a map in Scala with examples

 197 total views,  1 views today

Welcome to Scala series. In this post, you will learn 2 ways to iterate a map in Scala with examples.

Using for loop

This is a imperative style programming

object StaticReference {

  def main(args: Array[String]) {
    val map = Map("apple" -> 1, "orange" -> 2, "banana" -> 3)

    for ((key, value) <- map) {

      println("key is " + key + " value is " + value);
    }
  }
}

Output

key is apple value is 1
key is orange value is 2
key is banana value is 3

Using foreach

This is functional style programming

object StaticReference {

  def main(args: Array[String]) {
    val map = Map("apple" -> 1, "orange" -> 2, "banana" -> 3)
    map.foreach({ case (key, value) => println("key is " + key + " value is " + value) })
  }
}

Output

key is apple value is 1
key is orange value is 2
key is banana value is 3

These are the 2 ways of iterating a map in Scala.

References Official documentation

Please leave us a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.