1. Overview

In this tutorial, we’ll see how we can use the Scala foreach() method in collections.

2. Using the foreach() Method in Scala Collections

A common way to loop through Scala collections is to use the foreach() method. This method receives a function that is applied to each element:

scala> List(1,2,3).foreach(elem => println(elem))
1
2
3

The above code allows us to iterate through each element of the given list and do any sort of operation. In this case, we chose to print the element. It’s important to note that any returned value from the passed function is ignored.

We can further reduce the code by using the Scala underscore syntax:

scala> List(1,2,3).foreach(println(_))
1
2
3

scala> List(1,2,3).foreach(println)
1
2
3

We can see that the behavior is the same for any of the three approaches.

Moreover, we can apply the same foreach() method to any of the other Scala collections. Here’s what it would like for Sets:

scala> Set(1,2,3).foreach(println)
1
2
3

Let’s use it on an Array:

scala> Array(1,2,3).foreach(println)
1
2
3

Finally, we’ll use it on a Sequence and a Vector:

scala> Seq(1,2,3).foreach(println)
1
2
3
scala> Vector(1,2,3).foreach(println)
1
2
3

We can even apply the same logic to more complex collections like Maps:

scala> Map(1 -> "a", 2 -> "b", 3 -> "c").foreach(println)
(1,a)
(2,b)
(3,c)

If we need to deconstruct the element, we can make use of the case statement as well:

scala> Map(1 -> "a", 2 -> "b", 3 -> "c").foreach{ case (k,v) => println(s"The value for key ${k} is: ${v}") }
The value for key 1 is: a
The value for key 2 is: b
The value for key 3 is: c

This is a shorthand provided by Scala syntax. However, while it’s probably not as readable, we could achieve the same with the previous approach as well:

scala> Map(1 -> "a", 2 -> "b", 3 -> "c").foreach(elem => println(s"The value for key ${elem._1} is: ${elem._2}"))
The value for key 1 is: a
The value for key 2 is: b
The value for key 3 is: c

And we get exactly the same output.

3. Conclusion

In this article, we saw how to iterate on the many different collections in Scala using the foreach() method. This method allows us to apply any operation to each of the elements sequentially.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.