Home »
Scala
SortedMap foreach() Method in Scala
By IncludeHelp Last updated : November 14, 2024
Map is a collection that stores its elements as key-value pairs, like a dictionary. SortedMap is a special type of map in which elements are sorted in ascending order.
SortedMap find() Method
SortedMap foreach() method is used to perform a given operation defined in the function on each element of the sortedMap. The method takes each element, passes it through the function and returns the value in a sortedMap.
Syntax
SortedMap_Name.foreach(processingFunction)
Parameters
The method accepts a function as a parameter which is a processing function.
Return Type
It returns a sortedMap with resulting values after applying the function.
Example 1
We will print the square of each element of the sortedMap
import scala.collection.SortedMap
object MyObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad", 11 -> "Indore")
println("The Sorted Map is " + mySortedMap)
// Define a square function
def square(x: Int): Int = x * x
// Using foreach to print the square of each key in the map
mySortedMap.foreach { case (key, _) => println(square(key)) }
}
}
Output
The Sorted Map is TreeMap(1 -> Delhi, 2 -> Mumbai, 8 -> Hyderabad, 11 -> Indore)
1
4
64
121
The foreach() method is generally used to print the elements of the sortedMap.
Example 2
Print all elements of the sortedMap
import scala.collection.SortedMap
object MyObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad", 11 -> "Indore")
println("The Sorted Map is " + mySortedMap)
println("Printing sorted map using foreach method")
// Iterating and printing each element in the map
mySortedMap.foreach { case (index, value) =>
println(s"Index -> $index , Value -> $value")
}
}
}
Output
The Sorted Map is TreeMap(1 -> Delhi, 2 -> Mumbai, 8 -> Hyderabad, 11 -> Indore)
Printing sorted map using foreach method
Index -> 1 , value -> Delhi
Index -> 2 , value -> Mumbai
Index -> 8 , value -> Hyderabad
Index -> 11 , value -> Indore