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?
Even though Stream does not implement Iterable, it has a method iterator() that matches the shape of the abstract method of the Iterable interface.
The Collection interface extends Iterable , so all subtypes of Collection also implement the Iterable interface.
Stream. iterate() method works just like a function-of algebraic operation which is commonly written as ƒ(x). The method first returns the seed-value itself. For the 2nd element in the Stream it finds ƒ(seed-value) and from then on iteratively keeps applying function-of to the returned values.
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
Iterableimplies reusability, whereasStreamis something that can only be used once — more like anIterator.If
StreamextendedIterablethen existing code might be surprised when it receives anIterablethat throws anExceptionthe second time they dofor (element : iterable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With