Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of Collection.stream()

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():

  1. Where do I get the java.util.stream.Stream from?
  2. How did they implement it without actually "disturbing" the existing collections?(assuming that they did not touch them)

I did try to look through the documentations of java.util.AbstractCollection and java.util.AbstractList but was unable to find it.

like image 441
Adit A. Pillai Avatar asked May 30 '17 09:05

Adit A. Pillai


2 Answers

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.

like image 113
Jeremy Grand Avatar answered Oct 11 '22 13:10

Jeremy Grand


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.

like image 38
Tamas Hegedus Avatar answered Oct 11 '22 14:10

Tamas Hegedus