for
scala> val names = Array("Andy","Jack","Sam","Daniel")
names: Array[String] = Array(Andy, Jack, Sam, Daniel)
scala> for(name <- names) println(name)
Andy
Jack
Sam
Daniel
scala> for(name <- names) {
| var upperName = name.toUpperCase
| println(upperName)
| }
ANDY
JACK
SAM
DANIEL
foreach
scala> names.foreach(println)
Andy
Jack
Sam
Daniel
scala> 1.to(5).foreach(println)
1
2
3
4
5
scala> (1 to 5).foreach(println)
1
2
3
4
5
使用 withFilter 過濾元素
scala> names.withFilter(_ != "Sam").foreach(println)
Andy
Jack
Daniel
scala> for(i <- 0 until newNames.length) {
| println(s"$i is ${newNames(i)}")
| }
0 is ANDY
1 is JACK
2 is SAM
3 is DANIEL
迴圈搭配條件式 :
scala> val names = Array("a1"->"Sam" , "a2"->"Daniel" , "a3"->"Jack" , "a4"->"Ray")
scala> for(i <- 0 until names.length if names(i)._2 != "Daniel") {
| println(names(i))
| }
(a1,Sam)
(a3,Jack)
(a4,Ray)
zip 可指定 index 開始的數字,zipWithIndex 則是從 0 開始 :
scala> for((element , index) <- newNames.zip(Stream from 5)) {
| println(s"$index is $element")
| }
5 is ANDY
6 is JACK
7 is SAM
8 is DANIEL
scala> for((element , index) <- newNames.zipWithIndex) {
| println(s"$index is $element")
| }
0 is ANDY
1 is JACK
2 is SAM
3 is DANIEL
scala> val days = Array(("Sunday",0), ("Monday",1))
days: Array[(String, Int)] = Array((Sunday,0), (Monday,1))
scala> days.zipWithIndex.foreach {day => println(s"${day._1._1} is ${day._1._2} , index is ${day._2}")}
Sunday is 0 , index is 0
Monday is 1 , index is 1
for 迴圈多個計數器變數的寫法 :
scala> for (i <- 1 to 3;j <- -2 to -1;k <- 8 to 10) {println(s" i=$i , j=$j , k=$k ")}
i=1 , j=-2 , k=8
i=1 , j=-2 , k=9
i=1 , j=-2 , k=10
i=1 , j=-1 , k=8
i=1 , j=-1 , k=9
i=1 , j=-1 , k=10
i=2 , j=-2 , k=8
i=2 , j=-2 , k=9
i=2 , j=-2 , k=10
i=2 , j=-1 , k=8
i=2 , j=-1 , k=9
i=2 , j=-1 , k=10
i=3 , j=-2 , k=8
i=3 , j=-2 , k=9
i=3 , j=-2 , k=10
i=3 , j=-1 , k=8
i=3 , j=-1 , k=9
i=3 , j=-1 , k=10
scala> for{
| i <- -3 to 0
| j <- 1 to 3
| if i != 2 && j != 2
| } println(s"i = $i , j = $j")
i = -3 , j = 1
i = -3 , j = 3
i = -2 , j = 1
i = -2 , j = 3
i = -1 , j = 1
i = -1 , j = 3
i = 0 , j = 1
i = 0 , j = 3
透過 Loop 及 yield 處理過元素後,可產生新的 collection :
scala> val newNames = for(name <- names) yield name.toUpperCase
newNames: Array[String] = Array(ANDY, JACK, SAM, DANIEL)
for(int i = 0 ; i < e.length ; i++) ...
for(String name : names) ...
scala :
for(i <- 0 until e.length) ...
for(name <- names) ...