peek() method is an intermediate Stream operation. So process the Stream element through
peek(), we must use a terminal operation.
Stream.peek()without any terminal operation does nothing.
1. Stream peek() Method
1.1. Method Syntax
peek() returns a new Stream consist of elements from the original Stream.
action is a non-interfering action to perform on the elements as they are consumed from the Stream. The result elements after performing the
action are placed into the new Stream.
Stream<T> peek(Consumer<? super T> action)
peek()method is an intermediate operation.
- It returns a Stream consisting of the elements of current stream.
- It additionally perform the provided
actionon each element as elements.
- For parallel stream pipelines, the
actionmay be called at whatever time and in whatever thread the element is made available by the upstream operation.
- If the
actionmodifies shared state, it is itself responsible for providing the required synchronization.
peek()exists mainly to support debugging, where we want to see the elements as they flow past a certain point in a pipeline.
2. Java 8 Stream peek() Example
2.1. Using peek() method without terminal operation
As mentioned above,
Stream.peek() without any terminal operation does nothing.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.stream() .peek( System.out::println ); //prints nothing
2.1. Using peek() method with terminal operation
Java program to use
peek() API to debug the Stream operations and logging Stream elements as they are processed.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); List<Integer> newList = list.stream() .peek(System.out::println) .collect(Collectors.toList()); System.out.println(newList);
1 2 3 4 5 [1, 2, 3, 4, 5]
Stream.peek() method can be useful in visualizing how the stream operations behave and understanding the implications and interactions of complex intermediate stream operations.
Though it is entirely possible to alter the inner state of elements in the Stream, it is never recommended and shall be avoided.
Happy Learning !!