jakchang
jakchang

Reputation: 452

why is it possible that the stream::iterator returns to Iterable in java?

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.

Upvotes: 0

Views: 61

Answers (1)

BambooleanLogic
BambooleanLogic

Reputation: 8161

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

Upvotes: 5

Related Questions