Why is Stream<T> not an Iterable<T> ?

Paul Sandoz paul.sandoz at oracle.com
Wed Mar 27 02:31:41 PDT 2013

On Mar 27, 2013, at 4:05 AM, Sam Pullara <spullara at gmail.com> wrote:

> Iterable<T> can be iterated over and over because each time you call .iterator() you get a new instance starting from the beginning. Stream is more closely related to Iterator<T>. It would be very hard to insure that existing APIs that take Iterable would work with Streams because of this property. Even wrapping it would be a bit painful as you would have to buffer the full Stream to implement the Iterable contract.

Yes, a previous version of the API was based on composing Iterables, but it was complex. In the context of streams even Iterator is a poor interface to use for composing, since we need to evaluate sequentially or in parallel and short-circuit.

The current implementation has been simplified down to a composition approach that uses neither Iterable nor Iterator. Note that it is still possible to transform a Stream into an Iterator. We refer to that as the "escape-hatch" to be used when it is not possible to achieve what you want with the operations on Stream.


> Sam
> On Mar 26, 2013, at 7:56 PM, Oliver Doepner <odoepner at gmail.com> wrote:
>> Hello,
>> I recently joined this mailing list. I am quite excited about the
>> lambda functionality coming in Java 8.
>> I also had the pleasure to attend Brian's "Road to Lambda" talk at JavaOne.
>> Thanks for the great work.
>> Today I looked at the Javadoc at
>> http://lambdadoc.net/api/java/util/stream/Stream.html
>> http://lambdadoc.net/api/java/lang/Iterable.html
>> I hope that site has recent information. I had some problems finding
>> the source itself on hg.
>> I probably misunderstood the (not so obvious?) links at
>> http://hg.openjdk.java.net/lambda/lambda/.
>> Anyhow, I noticed that both of the methods of Iterable (iterator,
>> forEach) are also present on Stream.
>> Now I wonder why Stream<T> does not extend Iterable<T>.
>> Then I searched the lambda-dev archives for threads related to Iterables.
>> I did not find a discussion directly related to this. I hope I didn't
>> miss anything.
>> I think that it would be nice if Stream instances could be passed to
>> existing APIs that take Iterable.
>> Naively speaking: Why have the same methods with the same signatures
>> and semantics / Javadoc on two core Java interfaces and not make one a
>> subtype of the other? That feels like a pair of quack-like-a-ducks
>> calling for subtyping. :^)
>> Thanks
>> Oliver
>> -- 
>> Oliver Doepner
>> http://doepner.net/

More information about the lambda-dev mailing list