I have been working on JDK 1.8 for a few days now where I came across some piece of code which was similar to this:
List<Integer> list = Arrays.asList(1,2,3,4,5);
list.stream();
Now, easy and clean as it may appear to the people who have been working with streams (java.util.stream
), I could not find the the actual class that implements the java.util.Collection.stream()
method.
I have the following questions, when I say list.stream()
:
java.util.stream.Stream
from?I did try to look through the documentations of java.util.AbstractCollection
and java.util.AbstractList
but was unable to find it.
Java 8 allows the definition of default methods in interfaces.
Collection<E>
then defines :
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
That's how they added it.
As others pointed out, the .stream()
method is implemented as a default method in the Collection
interface itself, as you can see it in the method signature in the official documentation:
default Stream<E> stream()
How the stream interface is implemented is an implementation detail of the collection. However, implementing the same heavy Stream
interface for every collection would be a lot of work and duplication, so they use an intermediate abstraction called Spliterator.
This SO thread on .stream()
might be worth reading as well.
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