Home  >  Java 8

Java Stream peek()

By Arvind Rai, June 05, 2020
This page will walk through Stream.peek method example. The peek method returns the stream consisting the elements of this stream and performs the provided Consumer action on each element. The peek is an intermediate operation.
Find the peek method syntax from Java doc.
Stream<T> peek(Consumer<? super T> action) 
Parameters: Pass the Consumer as action.
Returns: The method returns a new stream.

The peek method is mainly used for debugging to see the elements as they flow past a certain point in a pipeline.
In parallel stream operation, the action of peek method may be called at whatever time and in whatever thread the element is made available by the upstream operation.
The peek method is intermediate method and will execute when terminal method is called. But in Java 9, for the short-circuiting operations like count(), the action in peek method will not be invoked for those elements.

Stream.peek() : An Intermediate Operation

The peek method is the intermediate method, so it will not execute until the terminal method is invoked. Let us see by the example. Find the peek method on which we are not calling any terminal method.
Stream.of(10, 20, 30).peek(e -> System.out.println(e)); 
There will be no output.
Now use a terminal method in the above code and we will get the output for peek method.
Stream.of(10, 20, 30).peek(e -> System.out.println(e))
    .collect(Collectors.toList()); 
Find the output.
10 20 30 

peek() Example

The peek method is used mainly for debugging. Find the examples.
Example-1: We have a stream of integers. First we will filter and then debug and then map it and then again debug.
Stream.of(10, 11, 12, 13)
 .filter(n -> n % 2 == 0)
 .peek(e -> System.out.println("Debug filtered value: " + e))
 .map(n -> n * 10)
 .peek(e -> System.out.println("Debug mapped value: " + e))
 .collect(Collectors.toList()); 
Output
Debug filtered value: 10
Debug mapped value: 100
Debug filtered value: 12
Debug mapped value: 120 

Example-2: In this example we have a list of duplicate values. We will find distinct values and debug it using peek method.
List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
String output = list.stream()
	.distinct()
	.peek(e -> System.out.println("Debug value: " + e))
	.collect(Collectors.joining(","));
System.out.println(output); 
Output
Debug value: AA
Debug value: BB
Debug value: CC
AA,BB,CC 

Example-3: In this example we will store data in the list using peek method.
PeekDemo.java
package com.concretepage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PeekDemo {
  public static void main(String[] args) {
	List<String> debugList = new ArrayList<>();
        List<String> names = Arrays.asList("Mahesh", "Suresh", "Mahendra");
        names.stream()
         .filter(el -> el.startsWith("M"))
         .peek(e -> debugList.add(e))
         .collect(Collectors.toList());
        System.out.println(debugList);
  }
} 
Output
[Mahesh, Mahendra] 

peek() Example with Parallel Stream

We know that in parallel stream operation, the peek method may be called at whatever time and in whatever thread the element is made available by the upstream operation. So the element received by peek method may vary in order for multiple run. Find the example.
PeekDemoParallel.java
package com.concretepage;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PeekDemoParallel {
  public static void main(String[] args) {
    List<Integer> sortedList = Stream.of(15, 10, 17, 11)
      .parallel()
      .sorted()
      .peek(e -> System.out.println("Debug: " + e))
      .collect(Collectors.toList());
    
    System.out.println("---After sorting---");
    System.out.println(sortedList);
  }
} 
Output
Debug: 15
Debug: 11
Debug: 17
Debug: 10
---After sorting---
[10, 11, 15, 17] 

peek() with count() in Java 9

In Java 9, for the short-circuiting operations like count(), the action in peek method will not be invoked for those elements. The peek method does not inject into or remove elements from the stream. In a stream source the number of elements is known and count is the size of stream list, so there is no need to execute the pipeline. Find the code.
long cnt = Stream.of(10, 11, 12, 13)
  .peek(e -> System.out.println("Debug: " + e))
  .count();
System.out.println(cnt); 
The peek will not execute and the output will be only 4.

Reference

Java doc: Stream
POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us