Wednesday, February 2, 2022

Java Stream - peek() With Examples

In Java Stream API there is a peek() method that returns a stream consisting of the elements of this stream, additionally performing the provided action on each element. Reading this description may remind of you another method map() in Java Stream API which also does the job of returning a stream consisting of the results of applying the given function to the elements of this stream. But, don’t get confused they are different methods with different syntaxes peek() method takes a Consumer as an argument where as map() takes a Function as an argument. Note that Consumer just consumes the value and returns no result whereas Function accepts one argument and produces a result.

Syntax of peek() method

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

Method parameter is of type Consumer functional interface and method returns a new stream.

Some important points about peek() method.

  1. peek() is an intermediate operation.
  2. Intermediate operations are always lazy which means they won't start executing as and when encountered but only be executed when the steam pipeline starts to work. That means there must be a terminal operation at the end.
  3. As per Java documentation “This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline”. So the main task of peek() method is to use it display elements after certain tasks just to check if results are as intended or not.

peek() method Java examples

1. In the example peek() method is used to display the returned stream elements after each operation.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PeekStream {

  public static void main(String[] args) {
    List<String> nameList = Stream.of("Amit", "Benjamin", "Rimmi", "Joshua", "Paige")
             .filter(e -> e.length() > 5)
             .peek(e -> System.out.println("Filtered value: " + e))
             .map(String::toUpperCase)
             .peek(e -> System.out.println("Mapped value: " + e))
             .collect(Collectors.toList());
    
    System.out.println("Names after stream execution- " + nameList);
  }
}

Output

Filtered value: Benjamin
Mapped value: BENJAMIN
Filtered value: Joshua
Mapped value: JOSHUA
Names after stream execution- [BENJAMIN, JOSHUA]

If there is no terminal operation, intermediate operations like peek() are not executed. You can remove the terminal operation collect() from the above example to check that.

public class PeekStream {

  public static void main(String[] args) {
    Stream.of("Amit", "Benjamin", "Rimmi", "Joshua", "Paige")
             .filter(e -> e.length() > 5)
             .peek(e -> System.out.println("Filtered value: " + e))
             .map(String::toUpperCase)
             .peek(e -> System.out.println("Mapped value: " + e));
  }
}

No output on executing this code.

That's all for this topic Java Stream - peek() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Collectors.teeing() With Examples
  2. Java Stream - allMatch() With Examples
  3. collect() Method And Collectors Class in Java Stream API
  4. Java Stream - findFirst() With Examples
  5. Spliterator in Java

You may also like-

  1. JVM Run-Time Data Areas - Java Memory Allocation
  2. Difference Between HashMap And ConcurrentHashMap in Java
  3. Compact Strings in Java
  4. Java Multithreading Interview Questions And Answers
  5. Java Program to Get Current Date and Time
  6. CanDeactivate Guard in Angular With Example
  7. Run Python Application in Docker Container
  8. Fair Scheduler in YARN

No comments:

Post a Comment