Convert Iterable to Stream using Java 8 JDK Convert Iterable to Stream using Java 8 JDK java java

Convert Iterable to Stream using Java 8 JDK


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.


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

Streams.stream(iterable)


You can easily create a Stream out of an Iterable or Iterator:

public static <T> Stream<T> stream(Iterable<T> iterable) {    return StreamSupport.stream(        Spliterators.spliteratorUnknownSize(            iterable.iterator(),            Spliterator.ORDERED        ),        false    );}