Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Java Iterable to a Scala Iterable?

Is there an easy way to convert a

java.lang.Iterable[_] 

to a

Scala.Iterable[_] 

?

like image 269
Matt R Avatar asked Jul 02 '09 06:07

Matt R


People also ask

How to convert iterator to iterable in Java?

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.

How to get the iterable object from collection in Java?

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.

How to get stream from an iterable in Java?

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:

How to convert SPL iterator to sequential stream in Java?

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.


1 Answers

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) 

like image 156
Alex Cruise Avatar answered Oct 13 '22 08:10

Alex Cruise