Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
roim Avatar asked Nov 21 '13 19:11

roim


People also ask

Does stream implement Iterable?

Even though Stream does not implement Iterable, it has a method iterator() that matches the shape of the abstract method of the Iterable interface.

Do all collections implement Iterable?

The Collection interface extends Iterable , so all subtypes of Collection also implement the Iterable interface.

How does stream iterate work?

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.


1 Answers

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).

like image 57
kennytm Avatar answered Sep 28 '22 08:09

kennytm