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?
iterablejavajava-8java-stream
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?
Best Answer
Iterable
has aspliterator()
method, which you can pass toStreamSupport.stream
to create a stream: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 usesspliteratorUnknownSize
), but in the more common case, where yourIterable
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.