Reputation: 25
I've been trying to play around with stream operations, and am trying to understand why the following doesn't convert each integer to a string. My understanding of peek()
is that it acts as an intermediate operator, and applies the given operation to the stream if it is followed by a terminal operator. Any help would be great!
List<Integer> testList = Arrays.asList(10, 11, 12, 13, 14, 15);
testList.stream().peek(x -> x.toString()).forEach(x -> System.out.println(x.getClass()));
Upvotes: 2
Views: 3340
Reputation: 41
The method peek take a consumer as argument, and consumer just consumes elements it take a value as argument and returns a void, which means that the value returned here x -> x.toString()
is juste ignored by the JRE, also peek is destinated for debugging, peek means look but don't touch. You want to use map instead.
Upvotes: 0
Reputation: 89214
peek
performs the operation on each stream element, but does not modify the stream. It is often used to print the elements of a Stream
before or after some operations for debugging, e.g. stream.peek(System.out::println)
. The documentation for peek
states that it:
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
You are looking for Stream#map
, which converts each element of the Stream
to the result of the function when called with the element. According to the documentation, it:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
Upvotes: 3
Reputation: 111219
The peek
operator makes no changes to the stream. It only allows you to look at the items that are flowing through the pipeline in the location where you put it, as if it was a window. You cannot transform the items, or filter them, or otherwise modify the stream - there are other operators for that (such as map
and filter
).
You can find a longer discussion on Stream.peek
here: https://www.baeldung.com/java-streams-peek-api
Upvotes: 0