Java 8 Streams peek() Method

Java 8 Stream provides a different approach to process the data. In this article we will look at Java 8 Streams peek method.

 

Introduction

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 peek() method.

  1. This is an intermediate operation. It does not operate on the entire collection until terminal operation (More details in the latter section)
  2. Returns stream comprises current stream.
  3. 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

output

 No output 

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

Console Output

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:

  1. Source – The source data for the stream API.
  2. Intermediate Operations – Optional intermediate operations on the stream.
  3. 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 (collect(Collectors.toList())).

 

Summary

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 Sharma

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.

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of