Stream.peek()without any terminal operation does nothing.
1. Stream.peek() – Syntax
Stream<T> peek(Consumer<? super T> action)
action is a non-interfering action to perform on the elements as they are consumed from the stream. This method returns a new stream consist of elements of the original stream.
2. Stream.peek() – Description
- Stream.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.
- This method exists mainly to support debugging, where we want to see the elements as they flow past a certain point in a pipeline.
3. Java Stream peek() example
3.1. 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
3.2. With terminal operation
Stream.peek() with the terminal operation perform the debug operation as well.
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 a useful in visualizing how 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, but it is never recommended and shall be avoided.