I\'m writing some Scala code which uses the Apache POI API. I would like to iterate over the rows contained in the java.util.Iterator
that I get from the Sheet
If you are iterating through a large dataset, then you probably don't want to load whole collection into memory with .asScala
implicit conversion. In this case, a handy way approach is to implement scala.collection.Iterator
trait
import java.util.{Iterator => JIterator}
def scalaIterator[T](it: JIterator[T]) = new Iterator[T] {
override def hasNext = it.hasNext
override def next() = it.next()
}
val jIterator: Iterator[String] = ... // iterating over a large dataset
scalaIterator(jIterator).take(2).map(_.length).foreach(println) // only first 2 elements are loaded to memory
It has similar concept but less verbose IMO :)
As of Scala 2.8, all you have to do is to import the JavaConversions object, which already declares the appropriate conversions.
import scala.collection.JavaConversions._
This won't work in previous versions though.
There is a wrapper class (scala.collection.jcl.MutableIterator.Wrapper
). So if you define
implicit def javaIteratorToScalaIterator[A](it : java.util.Iterator[A]) = new Wrapper(it)
then it will act as a sub class of the Scala iterator so you can do foreach
.