简体   繁体   English

Stream中filter()方法的实现在哪里<T>界面?

[英]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.此代码过滤调用流,然后打印所有大于 10 的元素。 Predicate 中的测试方法为我们完成了这项工作。

But where is the actually implementation for the filter() method that does return the "STREAM" that is more than 10?但是 filter() 方法的实际实现在哪里返回超过 10 的“STREAM”? That I don't understand.我不明白。

This question in some way also applies for the forEach() method.这个问题在某种程度上也适用于 forEach() 方法。 How does it iterate through the stream?它如何遍历流? Since filter() and forEach() methods are abstract in the interface stream and have no implementation.由于 filter() 和 forEach() 方法在接口流中是抽象的并且没有实现。

java.util.stream.ReferencePipline implements Stream<T>.filter() . java.util.stream.ReferencePipline实现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.抽象类 ReferencePipeline 具有 fileter() 方法的实现。

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这是源代码的链接: http : //hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/stream/ReferencePipeline.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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