Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-01 02:04:43 Viewed : 562
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:
scalaval myMap = Map("Alice" -> 25, "Bob" -> 30, "Charlie" -> 22)
1. Using a For-Each Loop:
scalafor ((key, value) <- myMap) { println(s"Key: $key, Value: $value") }
2. Using the foreach
Method:
scalamyMap.foreach { case (key, value) => println(s"Key: $key, Value: $value") }
3. Using map
and foreach
(functional approach):
scalamyMap.map { case (key, value) => println(s"Key: $key, Value: $value") }
4. Using a While Loop and an Iterator:
scalaval iterator = myMap.iterator while (iterator.hasNext) { val (key, value) = iterator.next() println(s"Key: $key, Value: $value") }
5. Using a for
comprehension (functional approach):
scalafor { (key, value) <- myMap } println(s"Key: $key, Value: $value")
6. Using a Tail-Recursive Function:
scalaimport 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:
scalafor (key <- myMap.keys) { val value = myMap(key) println(s"Key: $key, Value: $value") }
8. Using mapKeys
and mapValues
methods (functional approach):
scalamyMap.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.