In this tutorial we’ll see how to use Java Stream peek()
method with the help of few examples.
peek() method exists mainly to support debugging, where you want to see the elements as they flow from one operation to another with in the Stream pipeline.
Syntax of peek() method in Java Stream API
Stream<T> peek(Consumer<? super T> action)
Argument passed to the peek method is of type Consumer functional interface which represents a non-interfering action to perform on the elements as they are consumed from the stream. Method returns a new Stream.
peek() is an intermediate operation which means using peek() without any terminal operation will do nothing.
Java 9 onward, if the number of elements in Stream source is known in advance then no source elements will be traversed and no intermediate operations like peek() will be evaluated. This is a performance optimization.
Java Stream peek() examples
1. In this example peek() method is used to display the stream elements after each operation.
import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamPeek { public static void main(String[] args) { List<String> tempList = Stream.of("one", "two", "three", "four", "five") .filter(e -> e.length() > 3) .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(tempList); } }Output
Filtered value: three Mapped value: THREE Filtered value: four Mapped value: FOUR Filtered value: five Mapped value: FIVE [THREE, FOUR, FIVE]
As you can see peek() method is a good way to debug your Stream and see the results of the operation on the Stream.
2. If you don’t have a terminal operation, intermediate operations like peek() are not executed. You can see that by removing the collect() operation from the previous example.
public class StreamPeek { public static void main(String[] args) { Stream.of("one", "two", "three", "four", "five") .filter(e -> e.length() > 3) .peek(e -> System.out.println("Filtered value: " + e)) .map(String::toUpperCase) .peek(e -> System.out.println("Mapped value: " + e)); } }On executing it you won’t get any output.
That's all for the topic Java Stream peek() With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Java Stream Sort on Multiple Fields
- Java Stream – Convert a Stream to Set
- Java Lambda Expressions With Examples
- ArrayList Vs CopyOnWriteArrayList in Java
- LocalTime in Java With Examples
- Write to Excel File in Java Using Apache POI
- Installing Node.js and NPM on Windows
- Spring Boot and Dependency Injection
- Spring Bean Lifecycle Callback Methods
- Method Overloading in Python With Examples
No comments:
Post a Comment