Scala - Multiple ways to iterate over a Map in Scala

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-01 02:04:43 Viewed : 270


Iterating over a Map in Scala can be done in various ways, depending on your specific needs. Here are multiple ways to iterate over a Map in Scala with output:

Assuming you have a Map like this:

scala
val myMap = Map("Alice" -> 25, "Bob" -> 30, "Charlie" -> 22)

1. Using a For-Each Loop:

scala
for ((key, value) <- myMap) { println(s"Key: $key, Value: $value") }

2. Using the foreach Method:

scala
myMap.foreach { case (key, value) => println(s"Key: $key, Value: $value") }

3. Using map and foreach (functional approach):

scala
myMap.map { case (key, value) => println(s"Key: $key, Value: $value") }

4. Using a While Loop and an Iterator:

scala
val iterator = myMap.iterator while (iterator.hasNext) { val (key, value) = iterator.next() println(s"Key: $key, Value: $value") }

5. Using a for comprehension (functional approach):

scala
for { (key, value) <- myMap } println(s"Key: $key, Value: $value")

6. Using a Tail-Recursive Function:

scala
import scala.annotation.tailrec @tailrec def printMap(map: Map[String, Int]): Unit = { if (map.nonEmpty) { val ((key, value), remainingMap) = (map.head, map.tail) println(s"Key: $key, Value: $value") printMap(remainingMap) } } printMap(myMap)

7. Using keys and values methods:

scala
for (key <- myMap.keys) { val value = myMap(key) println(s"Key: $key, Value: $value") }

8. Using mapKeys and mapValues methods (functional approach):

scala
myMap.map { case (key, value) => val transformedKey = s"Transformed $key" val transformedValue = value * 2 println(s"Key: $transformedKey, Value: $transformedValue") }

These are various ways to iterate over a Map in Scala. You can choose the one that best suits your coding style and the specific requirements of your application.

Search
Related Articles

Leave a Comment: