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);
}
};
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With