Implementation of Collection.stream()

Viewed 2814

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.

6 Answers

"stream" is just a name to group the functional aspect behind. The real implementation is in the java.util.stream.ReferencePipeline class.

This is where you can see the code applied during intermediate and final operations. To go from a Collection to a Stream for example, you can follow the path

Collection::stream() -> StreamSupport::stream() -> ReferencePipeline.Head

We will get java.util.stream.Stream object from the Collection interface's default method stream(); and it is possible because of default methods which is introduced in Java 8.

Before java 8 we could only declare methods in an interface. From Java 8 we can also define methods or default methods in an interface.

In our case stream() is a default method from the interface Collection. For example in below case when you do list.stream() the default method stream() of Collection will get called and it will convert list of objects to Stream and return it back so that you can process it further as per your need using operations such as filter, map, flatMap etc.

List<String> list = Arrays.asList("abc","pqr","xyz");
Stream<String> stream = list.stream();
Related