第十章 Scala 容器基礎(十二):使用Iterators

Problem

    你須要在你的應用中使用iterator。算法

Solutionthis

    儘管使用帶有hasNext()和next()方法的iterator是很是通用的遍歷Java集合的方法。可是它們在Scala集合中並不常常被使用。由於Java集合有許多像map和foreach的方法讓讓你能夠輕鬆地實現本身的算法。必須澄清的是,在Scala中我從未直接使用過以下代碼:spa

// don't do this
val it = collection.iterator
while (it.hasNext) ...

    話雖如此,一些時候你仍是會用到一個iterator,一個最好的例子就是io.Source.fromFile方法。這個方法返回一個迭代器,這很是好,由於當你在使用很是大的文件的時候,把整個文件讀進內存並非一個好的選擇。scala

    對於iterator,最重要的一點是,當你使用完以後,它就不能用了。你能夠使用一個iterator來打印集合中元素,可是你只能用一次,當你再次調用的時候,你會發現,你什麼都得不到了。code

scala> val it = Iterator(1,2,3)
it: Iterator[Int] = non-empty iterator

scala> it.foreach(println)
1
2
3

scala> it.foreach(println)

    一個iterator不是一個集合;他只是給你一種一個接一個地訪問集合元素的方法。可是一個iterator定義了許多集合中才有的方法,包括foreach, map, flatMap, collect等。你也能夠吧一個iterator轉換稱爲一個集合。內存

scala> val it = Iterator(1,2,3)
it: Iterator[Int] = non-empty iterator

scala> it.toArray
res11: Array[Int] = Array(1, 2, 3)

scala> it.to
to              toArray         toBuffer        toIndexedSeq    toIterable      toIterator      toList          
toMap           toSeq           toSet           toStream        toString        toTraversable   toVector
相關文章
相關標籤/搜索