0

I'm reading effective java and have one question. I don't understand why the stream iterator returns to Iterable. As I know, The Iterable contains the Iterator Interface. But in stream api, this code is working, even though iterator doesn't inherit the Iterable.

    public static <E> Iterable<E> iterableOf(Stream<E> stream){
        return stream::iterator;
    }

I'm very confusing about this codes. Because there is no relation between Iterator and Iterable, excepting for that Iterable has Iterator.

jakchang
  • 402
  • 5
  • 13
  • Does this answer your question? [Why does Stream not implement Iterable?](https://stackoverflow.com/questions/20129762/why-does-streamt-not-implement-iterablet) – Dennis Kozevnikoff Jul 25 '22 at 15:08

1 Answers1

5

Iterable<E> is a functional interface. That means that any lambda meeting the criteria of its sole method, Iterable<E> iterator(), can act as an implementation of this interface.

That means that any lambda that takes no parameters and returns an Iterator<E> can be used as an instance of Iterable<E>.

Now, the notation stream::iterator is syntactic sugar for the lambda () -> stream.iterator(), which is a lambda that meets the above criteria. stream::iterator is thus a valid return value for a method that returns Iterable<E>.

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56