In this example, we used the peek() method in two different situations to count the number of elements that pass by this step of the stream and write a message in the console.
As described in Chapter 6, Parallel and Reactive Streams, Stream has a source, zero or more intermediate operations, and a final operation. In the first case, our final operation is the count() method. This method doesn't need to process the elements to calculate the returned value, so the peek() method will never be executed. You won't see any of the messages of the peek method in the console, and the value of the counter variable will be 0.
The second case is different. The final operation is the forEach() method, and in this case, all the elements ...