Scala SortedMap foreach() method with example

The foreach() method is utilized to apply the given function to all the elements of the SortedMap.

Method Definition: def foreach(f: ((A, B)) => Unit): Unit

Return Type: It returns all the elements of the SortedMap after applying the given function to each of them.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of foreach()
// method
import scala.collection.immutable.SortedMap
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating SortedMap
        val m1 = SortedMap(3 -> "geeks", 1 -> "for", 2 -> "cs", 6 -> "geeks")
          
        // Applying foreach method and 
        // displaying output 
        val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))
          
    }
}

chevron_right


Output:



key=1, value=for
key=2, value=cs
key=3, value=geeks
key=6, value=geeks

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of foreach()
// method
import scala.collection.immutable.SortedMap
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating SortedMap
        val m1 = SortedMap(3 -> "geeks", 1 -> "for", 2 -> "cs", 3 -> "geeks")
          
        // Applying foreach method and 
        // displaying output 
        val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))
          
    }
}

chevron_right


Output:

key=1, value=for
key=2, value=cs
key=3, value=geeks

So, the identical elements are taken only once.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.