Is there an easy way to convert a
java.lang.Iterable[_]
to a
Scala.Iterable[_]
?
In the first step, Get the Iterator. In the second step, we will convert Iterator into Iterable without overriding an abstract method iterator (). In the third step, we will return Iterable from the method convertIteratorToIterable () and passed the Iterator object and get Iterable.
We will get the Iterator object by using iterator () method of Collection. We will get the Iterable object by overriding an iterator () method. We will define another method and in this method, we will pass the Iterator object and override iterator () method and then return Iterator object.
The Iterable interface is designed keeping generality in mind and does not provide any stream () method on its own. Simply put, you can pass it to StreamSupport.stream () method and get a Stream from the given Iterable instance. Let's consider our Iterable instance:
Convert the Spliterator into Sequential Stream using StreamSupport.stream () method. Collect the elements of the Sequential Stream as an Iterable using collect () method. Return the Iterable.
In Scala 2.8 this became much much easier, and there are two ways to achieve it. One that's sort of explicit (although it uses implicits):
import scala.collection.JavaConverters._ val myJavaIterable = someExpr() val myScalaIterable = myJavaIterable.asScala
EDIT: Since I wrote this, the Scala community has arrived at a broad consensus that JavaConverters
is good, and JavaConversions
is bad, because of the potential for spooky-action-at-a-distance. So don't use JavaConversions
at all!
And one that's more like an implicit implicit: :)
import scala.collection.JavaConversions._ val myJavaIterable = someExpr() for (magicValue <- myJavaIterable) yield doStuffWith(magicValue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With