I have this code
Integer[] i = {1,3,4,6,7,43,2,1};
//create a predicate
Predicate<Integer> ini = value -> value > 10;;
//display-filter-and print the values in the collection
List<Integer> sss =Stream.of(i).peek(e -> System.out.println(e)).filter(ini).
peek(value -> System.out.println("After filter " + value)).collect(Collectors.toList());
//display the filtered list
System.out.println(sss);
And I'm getting this result
1
3
4
6
7
43
After filter 43
2
1
[43]
My question is why I'm getting the filter message in between in the middle of the peek statement? I tried this in different IDEs but I'm getting the same results.
Why are you surprised?
You have two peek()
method calls. The first one is before the filter and the second after the filter.
Your stream pipeline consumes one element at a time (and that takes place as a result of executing the terminal operation collect()
).
Consuming an element of your stream involves applying the first peek()
, which prints the element, followed by applying the filter.
Only if the element passes the filter, the second peek()
is applied, and prints "After filter ..".
The only element that passes the filter is 43, which results in
43
After filter 43
being printed when it is consumed.
Only later the remaining elements are consumed, and printed when the first peek
is applied on them.