Java 8 Stream peek Sample

Java 8 Stream peek operation will return a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

The peek() operation is an intermediate operation, which means it return a new stream. So peek() creates a new Stream that contains the elements of the initial stream that match the given predicate.

Stream.peek() operation signature:

Stream<T> peek(Consumer<? super T> action)

Take a look at the sample code below that uses the peek() operation multiple times on the Stream of Strings.

//JavaCodeDepot Sample

import java.util.List;

public class JavaPeekSample {

	public static void main(String[] args) {

		List<String> jcdStreamStrings = Stream.of("fred", "barney", "wilma", "betty")
				.peek(val -> System.out.println("First Peek: " +val))
				.filter(val -> val.length() > 4)
				.peek(val -> System.out.println("Second Peek: " +val))
				.peek(val -> System.out.println("Third Peek: " +val))




First Peek: fred
First Peek: barney
Second Peek: barney
Third Peek: BARNEY
First Peek: wilma
Second Peek: wilma
Third Peek: WILMA
First Peek: betty
Second Peek: betty
Third Peek: BETTY

Let’s break down what is happening in the above sample Java code. The “First” call to peek() just prints out all four of the Strings in lower case as they are defined. The “Second” call to peek() is after a filter was set based on length, which is why “fred” did not get printed out. The “Third” call to peek() included the same 3 names as the second, but now all in upper case.

Stream.peek() operation of Java 8 is very hand to peek under the covers, so to speak, at the raw data contained within the Stream.

Add a Comment

Your email address will not be published. Required fields are marked *