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.
- peek() is an intermediate operation.
- 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.
- 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
You may also like-
No comments:
Post a Comment