第十章 Scala 容器基础(十):使用for循环来遍历一个集合

Problem

    我想使用for循环来遍历容器的全部元素,或者经过for yield来建立一个新的集合。app

Solution

    你能够使用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循环同样,执行多行的代码块:oop

scala> for (f <- fruits) {
     |   val s = f.toUpperCase
     |   println(s)
     | }
APPLE
BANANA
ORANGE

    使用一个计数器看成下标来访问一个集合:ui

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

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:code

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
The for/yield construct

    当你想经过一个现有的集合,对其元素进行加工后生成一个新的集合,那么就能够使用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后面的操做函数时:ip

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)
Map

    使用for循环来遍历一个Map一样也是很是方便的:element

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

Discussion

    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 ...”:get

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)
相关文章
相关标签/搜索