Why does Stream<T> not implement Iterable<T>?
People have already asked the same on the mailing list ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not.
I think the main reason is that
Iterable
implies reusability, whereasStream
is something that can only be used once — more like anIterator
.If
Stream
extendedIterable
then existing code might be surprised when it receives anIterable
that throws anException
the second time they dofor (element : iterable)
.
To convert a Stream
to an Iterable
, you can do
Stream<X> stream = null;
Iterable<X> iterable = stream::iterator
To pass a Stream
to a method that expects Iterable
,
void foo(Iterable<X> iterable)
simply
foo(stream::iterator)
however it probably looks funny; it might be better to be a little bit more explicit
foo( (Iterable<X>)stream::iterator );
I would like to point out that StreamEx
does implement Iterable
(and Stream
), as well as a host of other immensely awesome functionality missing from Stream
.