3

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()));

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.