Why does Stream<T> not implement Iterable<T>?

roim picture roim · Nov 21, 2013 · Viewed 38.8k times · Source

In Java 8 we have the class Stream<T>, which curiously have a method

Iterator<T> iterator()

So you would expect it to implement interface Iterable<T>, which requires exactly this method, but that's not the case.

When I want to iterate over a Stream using a foreach loop, I have to do something like

public static Iterable<T> getIterable(Stream<T> s) {
    return new Iterable<T> {
        @Override
        public Iterator<T> iterator() {
            return s.iterator();
        }
    };
}

for (T element : getIterable(s)) { ... }

Am I missing something here?

Answer

kennytm picture kennytm · Nov 21, 2013

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, whereas Stream is something that can only be used once — more like an Iterator.

If Stream extended Iterable then existing code might be surprised when it receives an Iterable that throws an Exception the second time they do for (element : iterable).