Implementation of Collection.stream()

Adit A. Pillai :

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.

Jeremy Grand :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430031&siteId=1