Iterate a List in Scala using ‘for loop’ and foreach

 207 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn how to iterate a List in Scala using for loop and foreach.

Let us create a list

var arr = List(1, 2, 3, 4, 5, 6)

Iterate a List using for loop in Scala

 def main(args: Array[String]) {

    //Iterate List
    var arr = List(1, 2, 3, 4, 5, 6)
    for (i <- arr) {
      println(i)
    }

  }

Output

1
2
3
4
5
6

Iterate a list in reverse using for loop in Scala

def main(args: Array[String]) {

    //Iterate List in reverse
    var arr = List(1, 2, 3, 4, 5, 6)
    for (i <- arr reverse) {
      println(i)
    }

  }

Output

6
5
4
3
2
1

Iterate a list using foreach in Scala

 def main(args: Array[String]) {

    //Iterate List in reverse
    var arr = List(1, 2, 3, 4, 5, 6)
    arr.foreach(println)

  }

Output

1
2
3
4
5
6

References : Scala Documentation

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!.