Scala List/foreach FAQ: How do I iterate over a Scala List using the foreach method and for loop?
There are a number of ways to iterate over a Scala List using the foreach operator and for comprehension, and I'll show a few of those approaches here.
Iterating lists with foreach
A common way to iterate over a Scala List is with the foreach method. Here's a quote about the foreach method from the book Programming in Scala:
foreach takes a procedure (a function with a result type Unit) as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.
Here's a simple example showing how to use the foreach function to print every item in a List:
scala> val x = List(1,2,3) x: List[Int] = List(1, 2, 3) scala> x.foreach { println } 1 2 3
If you've used a programming language like Ruby, this syntax will look very familiar to you.
This next example shows a way to sum all the elements in a list using the foreach method:
scala> var sum = 0 sum: Int = 0 scala> val x = List(1,2,3) x: List[Int] = List(1, 2, 3) scala> x.foreach(sum += _) scala> println(sum) 6
Scala Lists and the for comprehension
The Scala for comprehension is not specific to lists, but is an extremely powerful way to operate on lists. Here's a simple example of how to iterate over a list using the for comprehension:
scala> val names = List("Bob", "Fred", "Joe", "Julia", "Kim") names: List[java.lang.String] = List(Bob, Fred, Joe, Julia, Kim) scala> for (name <- names) println(name) Bob Fred Joe Julia Kim
So far, so good. Now let's add a simple "if" clause to the for comprehension to print only the elements we want to print:
scala> val names = List("Bob", "Fred", "Joe", "Julia", "Kim") names: List[java.lang.String] = List(Bob, Fred, Joe, Julia, Kim) scala> for (name <- names if name.startsWith("J")) | println(name) Joe Julia
If you already know about the for comprehension, you know that you can add multiple if clauses, and much more functionality. I could easily write an entire tutorial on the Scala for comprehension, so to keep this tutorial short, I'll stop here for now.