Why can I call the stream () method on objects in a class that do not have the stream () method?


I'm a novice Java programmer at university. I discovered something today that broke one of my conceptions about how Java syntax works.

public class testClass {

ArrayList <String> persons = new ArrayList <String> ();

public void run(){
    Stream <String> personstream = persons.stream();

The method stream() is not found in the ArrayList class, yet it might appear as if it's there. When I move my mouse over the stream()-method in Eclipse, it says it's part of Collections, but I don't find the stream() method anywhere in its online documentation.

Why does it work to call the stream() method if it's not part of the class I'm calling it from?

Did you check the right class and Java version? Java 8's Collection (not Collections) has a stream() default method, which is inherited by ArrayList:

 * Returns a sequential {@code Stream} with this collection as its source.
 * <p>This method should be overridden when the {@link #spliterator()}
 * method cannot return a spliterator that is {@code IMMUTABLE},
 * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
 * for details.)
 * @implSpec
 * The default implementation creates a sequential {@code Stream} from the
 * collection's {@code Spliterator}.
 * @return a sequential {@code Stream} over the elements in this collection
 * @since 1.8
default Stream<E> stream() {
    return StreamSupport.stream(spliterator(), false);