O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required