🧑🎓 tltr
| |
Print is executed multiple times till the first value that matches both filter conditions is found.
❓Question
🕵️♂️ Explanation
Let’s simplify it
| |
This won’t do anything because there is no terminal operation which triggers the reading from the source stream.
By adding the peek, which is an intermediate operation, the behaviour won’t change.
| |
This findFirst (terminal operation) evaluates the pipeline.
| |
During the evaluation, the sinks are wrapped (combined) into one Sink. As a result, we get:
peekSinkfilter ASinkfilter BSinkfindFirstSink
While the sink is not cancelled (in our case findFirst has no value) and there is an element in the stream, the pipeline will try to advance, fetch the next element and pass it to the wrapped sink as above (top-down)
✅ Walkthrough
So we will have something like this (since the stream is not empty):

The stream: 1 2 3 4 5 6 7 8 9
1is passed topeeksinkpeekis executed,1is printed1passed tofilter Asinkfilter Ais executed,falseis returned(1>2), the sink is not cancelled, continue the while
2is fetched and passed topeeksinkpeekis executed,2is printed2passed tofilter Asinkfilter Ais executed,falseis returned(2>2), the sink is not cancelled, continue the while
3is fetched and passed topeeksinkpeekis executed,3is printed3passed tofilter Asinkfilter Ais executed,trueis returned(3>2)
3passed tofilter Bsinkfilter Bis executed,falseis returned(3>3), the sink is not cancelled, continue the while
4is fetched and passed topeeksinkpeekis executed,4is printed4passed tofilter Asinkfilter Ais executed,trueis returned(4>2)
4passed tofilter Bsinkfilter Bis executed,trueis returned(4>3)
4passed tofindFirstsink- saves the value inside the
findFirstwhich means the sink is cancelled, while interrupted
- saves the value inside the
4returned
Another Example
Let’s move the peek before the findFirst. Almost the same code, and different output
Output:
| |
The sink:
filter ASinkfilter BSinkpeekSinkfindFirstSink
✅ Walkthrough
So we will have something like this:
The stream: 1 2 3 4 5 6 7 8 9
1is passed tofilter Asinkfilter Ais executed,falseis returned(1>2), the sink is not cancelled, continue the while
2is fetched and passed tofilter Asinkfilter Ais executed,falseis returned(2>2), the sink is not cancelled, continue the while
3is fetched and passed tofilter Asinkfilter Ais executed,trueis returned(3>2)3passed tofilter Bsinkfilter Bis executed,falseis returned(3>3), the sink is not cancelled, continue the while
4is fetched and passed tofilter Asinkfilter Ais executed,trueis returned(4>2)4passed tofilter Bsinkfilter Bis executed,trueis returned(4>3)
4is passed topeeksink4is printed
4is passed tofindFirstsink- saves the value inside the
findFirstwhich means the sink is cancelled, while interrupted
- saves the value inside the
4returned