Updated April 4, 2023
Introduction to Scala foreach
Looping is an important concept in any programming languages be it Scala, java,etc.. With the help of loops over we can iterate over the elements are perform the operations needed. Suppose we have a list over in Scala which we want to iterate over and do the general operations over all the elements, for this Scala came up with ForEach method.
This ForEach function brings every item in the list one by one and performs the operations needed. This foreach function can be used to iterate over map also.
Method Definition
def foreach(f: ((A, B)) => Unit): Unit
def foreach(f:(A)⇒Unit):Unit
- This returns all the elements of a Map after applying the given function to each
- It is applicable to both Scala’s Mutable and Immutable collection. We can use this method to loop with all the elements.
- ForEach takes a function as an argument that takes an element as the input parameter and doesn’t return anything. It should of the same type as the type of collections used.
- ForEach method can be used with iterators also, but there is the difference over the method used over iterators, it leaves the iterator at its end when done and again calling next on the same will throw NoSuchElement exception, whereas for collection it leaves the element in the collection unchanged.
- The for each method is applicable for all the members in the collection and is applied to every element there.
Flow Chart for ForEach Loop
It checks for each element over the collection if elements are present then perform the operation if not then come out from the loop.
Here is a small flowchart showing how foreach works:
Example #1
Let us look into more details with some examples:-
Code:
object Demo {
def main(args: Array[String]) {
val it = Iterator("this","is","demo","foreach loop Example")
//println(it.foreach)
it.foreach(println)
}
}
Output:
//This will generate error over the iterator. No such Element found Exception.
Code:
it.next
Output:
Here we can see that with iterator we can use the for-each loop to iterate over the and when once the iteration is done .next method cannot find any element over.
Example #2
Let us iterate it over a list and see how for each loop works:
Code:
object Demo {
def main(args: Array[String]) {
val a = List("This","is","a","SAMPLE","Program","forEach")
a.foreach(x=> println(x.toUpperCase))
}
}
Output:
In this example, we can see that the foreach method was used to iterate over a list and we can perform certain operations over there.
Example #3
We can do certain operations using the foreach loop let us see an example over that:-
Code:
object Demo {
def main(args: Array[String]) {
var sum = 0
val l =List(1,2,3)
l.foreach(sum += _)
println(sum)
}
}
Output:
From the above example, we saw that we can do several operations over foreach on every element we have.
Scala Foreach Method
The Scala ForEach method can also be used with Set. It returns all the elements in the set after applying functions to them.
Let us see with an example:
Code:
object Demo {
def main(args: Array[String]) {
val a1 = Set(2,4,5,67,8)
a1.foreach(x=>println(x))
}
}
Output: This will print all the elements in a set.
The same method can be applied over the Stack Class in Scala traversing among all the elements in that Scala stack class.
We can create a stack class and use the foreach loop for traversing the element. Import the stack class first
Code:
import scala.collection.mutable._
object Demo {
def main(args: Array[String]) {
val a1 = Stack(6,5,4,3,5,6,4)
a1.foreach(x=>println(x))
}
}
Output: All the elements in the stack will be printed down:-
The same can be used over a treeset, Queue, Sorted Map, SortedSet. We can also make a new list inside for each loop in Scala. Let us see how it works:-
Code:
object Demo {
def main(args: Array[String]) {
var col = List[String]()
List("a","b","c").foreach(x=>{col = x :: col})
println(col)
}
}
Output:
Conclusion
Here we see the use of ForEach loop for the iteration of all the elements in a loop. this is an important concept used in Scala as it iterates over all the elements in the loop and does the required necessary thing needed. The Same can be used with Map, Sortedmap, Stack, Queue making it flexible for many collections used in Scala.
Recommended Articles
We hope that this EDUCBA information on “Scala foreach” was beneficial to you. You can view EDUCBA’s recommended articles for more information.