Scala Mutable 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:
// Scala program of foreach() // method import scala.collection.SortedMap // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating SortedMap val m 1 = SortedMap( 3 - > "Beginner" , 1 - > "for" , 2 - > "cs" , 6 - > "Beginner" ) // Applying foreach method and // displaying output val result = m 1 .foreach(x => println( "key=" + x. _ 1 + ", value=" + x. _ 2 )) } } |
Output:
key=1, value=for key=2, value=cs key=3, value=Beginner key=6, value=Beginner
Example #2:
// Scala program of foreach() // method import scala.collection.SortedMap // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating SortedMap val m 1 = SortedMap( 3 - > "Beginner" , 1 - > "for" , 2 - > "cs" , 3 - > "Beginner" ) // Applying foreach method and // displaying output val result = m 1 .foreach(x => println( "key=" + x. _ 1 + ", value=" + x. _ 2 )) } } |
Output:
key=1, value=for key=2, value=cs key=3, value=Beginner
So, the identical elements are taken only once.
Contact Us