Magnus
Magnus

Reputation: 728

Why can I call the stream() method on objects of a class that don't 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?

Upvotes: 0

Views: 2308

Answers (4)

user1907906
user1907906

Reputation:

This is valid Java 8 code:

List<String> persons = new ArrayList<>();
Stream<String> stream = persons.stream();

List<T>.stream() is available.

Upvotes: 1

Lukas Eder
Lukas Eder

Reputation: 221145

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);
}

Upvotes: 6

Anton Sarov
Anton Sarov

Reputation: 3748

ArrayList implements the Collection interface. This interface has the method stream()

Upvotes: 3

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

The method stream() is a default method defines in the interface java.util.Collection. Look at the source of java.util.Collection.

It uses the method splititerator() on java.util.ArrayList for the implementation.

Upvotes: 1

Related Questions