我想使用for循环来遍历容器的所有元素,或者通过for yield来创建一个新的集合。
你可以使用for循环遍历所有的Traversable类型(基本上所有的sequency都可以):
scala> val fruits = Traversable("apple", "banana", "orange") fruits: Traversable[String] = List(apple, banana, orange) scala> for (f <- fruits) println(f) apple banana orange scala> for (f <- fruits) println(f.toUpperCase) APPLE BANANA ORANGE
如果你的循环体代码很长,那么你同样可以像正常使用for循环一样,执行多行的代码块:
scala> for (f <- fruits) { | val s = f.toUpperCase | println(s) | } APPLE BANANA ORANGE
使用一个计数器当作下标来访问一个集合:
scala> val fruits = IndexedSeq("apple", "banana", "orange") fruits: IndexedSeq[String] = Vector(apple, banana, orange) scala> for (i <- 0 until fruits.size) println(s"element $i is ${fruits(i)}") element 0 is apple element 1 is banana element 2 is orange
你同样可以使用zipWithIndex方法来遍历集合的时候获取当前元素的索引:
scala> for ((elem, count) <- fruits.zipWithIndex) {println(s"element $count is $elem")} element 0 is apple element 1 is banana element 2 is orange
生成一个计数器来获取集合元素下标的另一个方法是zip stream:
scala> for ((elem,count) <- fruits.zip(Stream from 1)) {println(s"element $count is $elem")} element 1 is apple element 2 is banana element 3 is orange scala> for ((elem,count) <- fruits.zip(Stream from 0)) {println(s"element $count is $elem")} element 0 is apple element 1 is banana element 2 is orange
当你想通过一个现有的集合,对其元素进行加工后生成一个新的集合,那么就可以使用for yield这样形式:
scala> val fruits = Array("apple", "banana", "orange") fruits: Array[String] = Array(apple, banana, orange) scala> val newArray = for (e <- fruits) yield e.toUpperCase newArray: Array[String] = Array(APPLE, BANANA, ORANGE)
再看一下这个例子的另外两种形式,一个是当for循环方法体是多行的时候,另一个形式是当你想复用yield后面的操作函数时:
scala> val newArray = for (e <- fruits) yield { | val s = e.toUpperCase | s | } newArray: Array[String] = Array(APPLE, BANANA, ORANGE) scala> def upper(s: String):String = {s.toUpperCase} upper: (s: String)String scala> val newArray = for (e <- fruits) yield upper(e) newArray: Array[String] = Array(APPLE, BANANA, ORANGE)
使用for循环来遍历一个Map同样也是非常方便的:
scala> val names = Map("fname" -> "Ed", "lname" -> "Chigliak") names: scala.collection.immutable.Map[String,String] = Map(fname -> Ed, lname -> Chigliak) scala> for ((k,v) <- names) println(s"key: $k, value: $v") key: fname, value: Ed key: lname, value: Chigliak
When using a for loop, the <- symbol can be read as “in,” so the following statement can be read as “for i in 1 to 3, do ...”:
for (i <- 1 to 3) { // more code here ...
在使用for循环来遍历一个集合元素的时候,我们同样可以添加if字句来对元素进行过滤:
for { file <- files if file.isFile //file是一个文件 if file.getName.endsWith(".txt") //file后缀名为.txt } doSomething(file)