Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)
I have an interface that 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?

1 Answer

0 votes
by (46k points)

This is both easier and gets a better result.  Iterable should a spliterator() method, so you should just need that to get your espliterator. In the most serious case, it's the very code (the default implementation uses spliteratorUnknownSize), but in the more general case, where your Iterable is already a collection, you'll get a more reliable spliterator, and hence better stream doing (maybe even good parallelism). It's also less code:

StreamSupport.stream(iterable.spliterator(), false)

             .filter(...)

             .moreStreamOps(...);

As you can see, preparing a stream from an Iterable  is not very disturbing.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...