score:29
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
.
score:2
If you would like to avoid the implicits in scala.collection.JavaConversions you can use scala.collection.JavaConverters to convert explicitly.
scala> val l = new java.util.LinkedList[Int]()
l: java.util.LinkedList[Int] = []
scala> (1 to 10).foreach(l.add(_))
scala> val i = l.iterator
i: java.util.Iterator[Int] = java.util.LinkedList$ListItr@11eadcba
scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._
scala> i.asScala.mkString
res10: String = 12345678910
Note the use of the asScala
method to convert the Java Iterator
to a Scala Iterator
.
The JavaConverters have been available since Scala 2.8.1.
score:4
You could convert the Java collection to an array and use that:
val array = java.util.Arrays.asList("one","two","three").toArray
array.foreach(println)
Or go on and convert the array to a Scala list:
val list = List.fromArray(array)
score:5
With Scala 2.10.4+ (and possibly earlier) it is possible to implicitly convert java.util.Iterator[A] to scala.collection.Iterator[A] by importing scala.collection.JavaConversions.asScalaIterator. Here is an example:
object SpreadSheetParser2 extends App {
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import java.io.FileInputStream
import scala.collection.JavaConversions.asScalaIterator
val ios = new FileInputStream("data.xls")
val workbook = new HSSFWorkbook(ios)
var sheet = workbook.getSheetAt(0)
val rows = sheet.rowIterator()
for (row <- rows) {
val cells = row.cellIterator()
for (cell <- cells) {
print(cell + ",")
}
println
}
}
score:6
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 :)
score:9
For Scala 2.10:
// Feature warning if you don't enable implicit conversions...
import scala.language.implicitConversions
import scala.collection.convert.WrapAsScala.enumerationAsScalaIterator
score:15
The correct answer here is to define an implicit conversion from Java's Iterator
to some custom type. This type should implement a foreach
method which delegates to the underlying Iterator
. This will allow you to use a Scala for
-loop with any Java Iterator
.
score:35
Edit: Scala 2.13.0 deprecates scala.collection.JavaConverters
, so since 2.13.0 you need to use scala.jdk.CollectionConverters
.
Scala 2.12.0 deprecates scala.collection.JavaConversions
, so since 2.12.0 one way of doing this would be something like:
import scala.collection.JavaConverters._
// ...
for(k <- javaCollection.asScala) {
// ...
}
(notice the import, new is JavaConverters, deprecated is JavaConversions)
score:258
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.
Source: stackoverflow.com
Related Query
- Iterating over Java collections in Scala
- iterating over Scala collections in Java
- Using scala parallelism when iterating over a java converted List to immutable
- Iterating over java List that involves Java generics <?> in Scala
- Scala paging iterating over legacy java method until condition is met
- What's the new way to iterate over a Java Map in Scala 2.8.0?
- What advantages does Ceylon have over Java or Scala
- What advantages does Scala have over Java for concurrent programming?
- scala build up string from iterating over map
- Single iteration => Multiple output collections from Java to Scala
- Iterating over a HashMap of HashMaps in Java (or Scala)
- Simple use of Scala collections from Java not compiling with 2.11
- Scala converters convert Java collections to Wrapper objects
- How to bridge Scala case classes and collections to Java
- Cost of implicit conversion from java to scala collections
- Iterating over more than three arrays in Scala
- Datastax java driver, convert scala collections to java error
- scala 2.8 implict java collections conversions
- scala 2.8 implict java collections conversions
- Guidelines for writing Scala API as wrapper over Java API
- Auto conversion between scala and java collections when using scala.collection.JavaConversions._ in scala 2.8
- Scala given list map / filter / take without iterating over whole list
- Iterating over accumulo table with scala
- Version agnostic way to convert from Java to Scala collections and back
- Iterating over for an Array Column with dynamic size in Spark Scala Dataframe
- Working with collections of mixed complex Java generics in Scala 2.10
- Scala looping over a java function
- Re-using Java generic collections in Scala without trait Object
- Iterating over a List and waiting for a Future to complete in Scala
- Scala iterating through 2 collections and finding matches
More Query from same tag
- How expensive is type inference?
- Understanding a specific scala class extension construct
- Use the schema of a df in a schema definition for another df?
- generate random String that must Contains alphabets, number and Special Character (6-10 digits)
- Spray json parsing and NullPointerException
- How to vendor dependencies in an SBT project?
- Sbt Unresolved Dependencies (Not a valid command: gen-idea)
- Fast and safe conversion from string to numeric types
- How can I mark some ScalaTests so that they only execute when invoked explicitly
- Connect Four game in Scala
- How to manage partial matching with regex?
- create tuple with 4 elements using tuple with 3 elements and an extra object
- Convert non-ascii hyphen to ascii in Scala
- Update a multi-statement Slick 2.1 withDynSession block to Slick 3.0.3
- Scala : Collect with generics
- Scala - Iterator being 'consumed'
- Runtime of tail and init on List
- Rational code in scala
- Combine two MultiMaps in Scala
- Why doesn't MySQLDriver have a Nullable Column Option?
- How can we define filters/properties for a elasticsearch index using Spark with Scala?
- Making the features of test data same as train data after featureselection in spark
- HiveContext is not reading schema of an Orcfile
- How to test list of futures in Scala
- How to execute operation in scala with timeout?
- Behavior of flatMap when applied to List[Option[T]]
- convert play getIntList to scala List[Int] simply
- org.apache.spark.SparkException:Job aborted due to stage failure :java.lang.NullPointerException
- How to combine Play JSON objects with parser-combinator JSONObjects?
- How to get unique key values from List of maps in Scala