Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 552
Waseem Swaileh Avatar asked Sep 12 '25 13:09

Waseem Swaileh


1 Answers

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);
                }
            };
        }
    };
}
like image 137
ifloop Avatar answered Sep 14 '25 04:09

ifloop