How it works...

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 of the stream will be processed. In the console, you will see messages of both peek() and forEach() methods. The final value of the counter variable will be 1,000.

The peek() method is an intermediate operation of a stream. Like with all intermediate operations, they are executed lazily, and they only process the necessary elements. This is the reason why it's never executed in the first case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.125.123