Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Iterable to Stream using Java 8 JDK

I have an interface which returns java.lang.Iterable<T>.

I would like to manipulate that result using the Java 8 Stream API.

However Iterable can't "stream".

Any idea how to use the Iterable as a Stream without converting it to List?

like image 237
rayman Avatar asked May 29 '14 11:05

rayman


People also ask

Does Java 8 support streams?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.

How do I stream Iterable?

Converting Iterable to Stream 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.

How do I convert Iterable to collections?

To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport. stream(), the spliterator can be traversed and then collected with the help collect() into collection.


2 Answers

There's a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:

StreamSupport.stream(iterable.spliterator(), false)              .filter(...)              .moreStreamOps(...); 

As you can see, getting a stream from an Iterable (see also this question) is not very painful.

like image 179
Brian Goetz Avatar answered Oct 12 '22 13:10

Brian Goetz


If you can use Guava library, since version 21, you can use

Streams.stream(iterable) 
like image 33
numéro6 Avatar answered Oct 12 '22 12:10

numéro6