SortedMap foreach() Method in Scala with Example

Here, we will learn about the foreach() method of SortedMap method. It is used to perform a certain operation on all elements of the sortedMap. We will learn about foreach() method with examples.
Submitted by Shivang Yadav, on January 05, 2021

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)

Parameter: The method accepts a function as a parameter which is a processing function.

Return: It returns a sortedMap with resulting values after applying the function.

Example 1: We will print the square of each element of the sortedMap

// Program to illustrate the working of 
// foreach() method in Scala

import scala.collection.SortedMap

object myObject {
    def square(a : Int ) : Int = {
        return a*a;
    }

def main(args: Array[String]) {
        val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad" , 11 -> "Indore") 
        println("The Sorted Map is " + mySortedMap)  
        val filteredMap = mySortedMap.foreach(x => println ( square(x._1) ) ) 
    }
}

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

// Program to illustrate the working of 
// foreach() method in Scala

import scala.collection.SortedMap

object myObject {
def main(args: Array[String]) {
        val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad" , 11 -> "Indore") 
        println("The Sorted Map is " + mySortedMap)  
        println("Printing sorted map using foreach method")
        val filteredMap = mySortedMap.foreach(x => println ( "Index -> " + (x._1) + " , value -> " + (x._2) ) ) 
    }
}

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



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.