Reputation: 704
Is there any direct API to convert scala.collection.Iterator to java list.
I tried following things:
val xs = Iterator[POJO]
println("xs size : " + xs.size)
import com.google.common.collect.Lists;
val p = Lists.newArrayList(xs)
**output** :
xs size : 1
p : [empty iterator]
case 2:
val input:Iterator[POJO] = xs.asJava
val m = ImmutableList.copyOf(input)
println("m value : " + m.toString())
**output**:
xs size : 1
m value : []
case 3:
val n = xs.toList.asJava;
println("n value : " + n.toString())
**output**
n value : []
Upvotes: 0
Views: 1293
Reputation: 1986
Iterator can be consumed exactly once and I can see that you try to reuse the same iterator for the case 3 even though conversion itself is correct.
Below you can find simple function that converts scala iterator to java list using approach in case 3:
def iteratorToJavaList[T](iterator: Iterator[T]): java.util.List[T] = {
import collection.JavaConverters._
iterator.toList.asJava
}
and it can be used like this:
val scalaIterator = List(1, 2, 3).iterator
println(iteratorToJavaList(scalaIterator))
which results:
[1, 2, 3]
Upvotes: 4