简体   繁体   中英

Where is the implementation of the filter() method in the Stream<T> interface?

class App {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<>();

        myList.add(7);
        myList.add(18);
        myList.add(10);
        myList.add(24);
        myList.add(17);
        myList.add(5);

        Stream<Integer> stream = myList.stream();

        stream = stream.filter(n -> n > 10); // it returns a stream of elements more than 10

        stream.forEach(n -> System.out.print(n + " "));
    }
}

This code filters the invoking stream and then prints all the elements that are more than 10. The test method in the Predicate does that for us.

But where is the actually implementation for the filter() method that does return the "STREAM" that is more than 10? That I don't understand.

This question in some way also applies for the forEach() method. How does it iterate through the stream? Since filter() and forEach() methods are abstract in the interface stream and have no implementation.

java.util.stream.ReferencePipline implements Stream<T>.filter() .

@Override
public final Stream<P_OUT> filter(Predicate<? super P_OUT> predicate) {
    Objects.requireNonNull(predicate);
    return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE,
                                 StreamOpFlag.NOT_SIZED) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
            return new Sink.ChainedReference<P_OUT, P_OUT>(sink) {
                @Override
                public void begin(long size) {
                    downstream.begin(-1);
                }

                @Override
                public void accept(P_OUT u) {
                    if (predicate.test(u))
                        downstream.accept(u);
                }
            };
        }
    };
}

Abstract class ReferencePipeline have the implementation for the fileter() method.

Here is the link of Source code: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/stream/ReferencePipeline.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM