In this section we will learn what the Stream peek() method is and how to use it in Java.
What is Java Stream peek() Method?
The Java Stream peek() method is used to see each element in an upcoming stream.
This method basically takes a reference to another method and passes each element in the stream to that reference method.
But remember, we can’t use the peek() method to modify the elements of a stream! This method is here to just view these elements! If you want to modify the elements of a stream, then you can use the map() method instead.
Note: the method is an intermediate and lazy one.
Java peek() Method Syntax:
Stream<T> peek(Consumer<? super T> action)
peek() Method Parameters:
The method has one parameter and that is of type Consumer which is a functional interface.
Basically, this method needs a reference to another method.
Here’s the signature of the reference method:
- It has only one parameter, which is of the same type as the elements in the target stream.
- The return value of this method is void.
Note: we can create this reference method using the lambda expression or refer to an instance or static method that is already created and has the same signature.
peek() Method Return Value:
The return value of this method is a new stream.
peek() Method Exceptions:
The method might throw two exceptions and that is:
NullPointerException: We get this exception if the argument of this method is set to null.
ClassCastException: We get this exception if the data type of the reference method is of incompatible type compared to the data type of elements in the stream.
Example: using Stream peek() method
import java.util.stream.Stream; class Main{ public static void main(String[] args) { Stream<Integer> stream = Stream.of(20,2,3,4,5,6,7,8,9,10,3,23); stream.peek(e->System.out.println("The current element in the stream is: "+e)).map(e->e*10).forEach(e->System.out.println(e)); } }
Output:
The current element in the stream is: 20 200 The current element in the stream is: 2 20 The current element in the stream is: 3 30 The current element in the stream is: 4 40 The current element in the stream is: 5 50 The current element in the stream is: 6 60 The current element in the stream is: 7 70 The current element in the stream is: 8 80 The current element in the stream is: 9 90 The current element in the stream is: 10 100 The current element in the stream is: 3 30 The current element in the stream is: 23 230