snippetjavaCritical
Convert Iterable to Stream using Java 8 JDK
Viewed 0 times
streamiterablejavausingconvertjdk
Problem
I have an interface which returns
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?
java.lang.Iterable.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?
Solution
Iterable has a spliterator() method, which you can pass to StreamSupport.stream to create a stream:StreamSupport.stream(iterable.spliterator(), false)
.filter(...)
.moreStreamOps(...);
This is a much better answer than using
spliteratorUnknownSize directly, as it is both easier and gets a better result. 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.As you can see, getting a stream from an
Iterable (see also this question) is not very painful.Context
Stack Overflow Q#23932061, score: 728
Revisions (0)
No revisions yet.