Scala Map foreach() method with example
Last Updated :
13 Aug, 2019
The foreach() method is utilized to apply the given function to all the elements of the map.
Method Definition: def foreach(f: ((A, B)) => Unit): Unit
Return Type: It returns all the elements of the map after applying the given function to each of them.
Example #1:
object GfG
{
def main(args : Array[String])
{
val m 1 = Map( 3 - > "geeks" , 1 - > "for" , 2 - > "cs" , 6 - > "geeks" )
val result = m 1 .foreach(x => println( "key=" + x. _ 1 + ", value=" + x. _ 2 ))
}
}
|
Output:
key=3, value=geeks
key=1, value=for
key=2, value=cs
key=6, value=geeks
Example #2:
object GfG
{
def main(args : Array[String])
{
val m 1 = Map( 3 - > "geeks" , 1 - > "for" , 2 - > "cs" , 3 - > "geeks" )
val result = m 1 .foreach(x => println( "key=" + x. _ 1 + ", value=" + x. _ 2 ))
}
}
|
Output:
key=3, value=geeks
key=1, value=for
key=2, value=cs
So, the identical elements are taken only once.
Share your thoughts in the comments
Please Login to comment...