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
- This is an intermediate operation. It does not operate on the entire collection until terminal operation (More details in the latter section)
- Returns stream comprises current stream.
- It’s a like a debugging tool. It allows “performing the provided action on each element as elements are consumed from the resulting stream,”.
1. Java Stream peek() Example
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.
2. Intermediate and Terminal Operations
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:
- Source – The source data for the stream API.
- Intermediate Operations – Optional intermediate operations on the stream.
- Terminal Operations – Operations which collect and provide final output.
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.