2 ways to iterate a list in Scala with examples

 222 total views,  2 views today

Welcome to Scala series. In this post, you will learn 2 ways to iterate a list in Scala with examples

Using for loop

This is a imperative style programming

object StaticReference {

  def main(args: Array[String]) {
    val list = List(1, 2, 3, 4, 5)

    for (item <- list) {
      if (item % 2 == 0) {
        println(item + " is even")
      } else {
        println(item + " is odd")
      }
    }
  }
}

Output

1 is odd
2 is even
3 is odd
4 is even
5 is odd

Using foreach

This is functional style programming

object StaticReference {

  def main(args: Array[String]) {
    val list = List(1, 2, 3, 4, 5)

    list.foreach(item => {
      if (item % 2 == 0) {
        println(item + " is even")
      } else {
        println(item + " is odd")
      }
    })
  }
}

Output

1 is odd
2 is even
3 is odd
4 is even
5 is odd

These are the 2 ways of iterating a list in Scala.

References : Official documentation

Please leave us a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.