Iterating over Java collections in Scala

前端 未结 9 1323
不思量自难忘°
不思量自难忘° 2020-11-28 02:19

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

相关标签:
9条回答
  • 2020-11-28 02:53

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

    0 讨论(0)
  • 2020-11-28 02:54

    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.

    0 讨论(0)
  • 2020-11-28 02:58

    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.

    0 讨论(0)
提交回复
热议问题