Why does Stream not implement Iterable?

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?

9 Answers
9

Leave a Comment