Scala Tutorials : 7 Different ways to iterate over a array in scala
for loop is used to iterate over the elements in a collection, either to operate on each element in the collection, or to create a new collection from the existing collection. There are many ways to loop over Scala collections, including for loops, while loops, and collection methods like foreach, map, flatMap, and more. This video primarily focuses on the for loop and foreach method. val a=Array("Red","Green","Blue"); for(e<-a) println(e) This for loop syntax in scala is clean and neat. When your algorithm requires multiple lines, use the same for loop syntax in a block. for(e<-a) { val s=e.toUpperCase() println(s); } The above two examples perform an operation using the elements in an array, but they don’t return a value you can use, such as a new array. In some cases where you want to build a new collection from the input collection, we use the for/yield combination val newArray=for(e<-a) yield e.toUpperCase(); for(e<-newArray) println(e) If you need access to a index inside a for loop, we can use the below approach. for (i <- 0 until newArray.length) { println("Using Counters",newArray(i)); } Below for loop demonstrates how to use guards (if statements in for loops) for(i<- 1 to 50 if(i%2==0)) { println(i); } For example, when you’re working with Arrays and collection, we can also iterate over each element by calling the foreach method on the collection as follows: newArray.foreach(println); if we want to execute multiple lines, we can use foreach block as follows : newArray.foreach{ e=> val s=e.toUpperCase(); println(s); }
Download
0 formatsNo download links available.