I came across some clever code to convert an Iterator to a Stream from Karol on this post. I have to admit that I don't completely understand how the lambda is allowed to be assigned to the Iterable
type in the following code...
static <T> Stream<T> iteratorToFiniteStream(final Iterator<T> iterator) {
final Iterable<T> iterable = () -> iterator;
return StreamSupport.stream(iterable.spliterator(), false);
}
I decided to write my own small test to ensure that it compiles and executes, and it does.
public void printsStream_givenIterator()
{
Iterator<String> iterator = Arrays.asList("a", "b", "c").iterator();
final Iterable<String> iterable = () -> iterator;
StreamSupport.stream(iterable.spliterator(), false).forEach(s -> System.out.println(s));
}
// prints: abc
My understanding is that the lambda () -> iterator
is acting as a Supplier function.
Iterable isn't a FunctionalInterface so how can it be assigned this lambda?