Stream interface provides a peek(
Consumer<? super T> action) method. This method returns a new stream comprises the elements of the original element. Before we jump in to an example, let’s take a quick look at some important points of the
Let’s look at a simple example for better clarity. If we run the following program, you won’t see any output in the console:
List languages = Arrays.asList("Java", "C", "PHP","Scala", "Go"); languages.stream().peek(System.out::println); // this will print nothing
Above code will have no output. Let’s change our code a little to see if we are getting any output:
List < String > languages = Arrays.asList("Java", "C", "PHP", "Scala", "Go"); //languages.stream().peek(System.out::println); // earlier code List < String > newLangugaes = languages.stream().peek(System.out::println).collect(Collectors.toList()); // we use terminal operator
Java C PHP Scala Go
We did not saw any output with the first example because it’s an intermediate operation and we didn’t apply a terminal operation.
The Java 8 Stream API works in different steps and some of them are required while others are optional. Here is a high level list:
The distinction between this operation is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. They execute it only when a terminal operation invoked on that stream. If we look at our previous example, We only have output once we use the terminal operator (
In this short article, we saw the Java 8 Streams peek method. The
Stream.peek() method can be a useful in visualizing how stream operations behave.
Manish's primary interests are Java, Spring Boot and Spring. His focus is more toward the automations and testing.Manish love travelling and when not working, he might be exploring some new destination.