You are correct, "peek" in the English sense of the word means "look, but do not touch."
However the JavaDoc states:
peek
Stream peek(Consumer action)
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.
Key words: "performing ... action" and "consumed". The JavaDoc is very clear that we should expect peek to have the ability to modify the stream.
However the JavaDoc also states:
API Note:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
This indicates that it is intended more for observing, e.g. logging elements in the stream.
What I take from all of this is that we can perform actions using the elements in the stream, but should avoid mutating elements in the stream. For example, go ahead and call methods on the objects, but try to avoid mutating operations on them.
At the very least, I would add a brief comment to your code along these lines:
// Note: this peek() call will modify the Things in the stream.
streamOfThings.peek(this::thingMutator).forEach(this::someConsumer);
Opinions differ on the usefulness of such comments, but I would use such a comment in this case.
Answer from user22815 on Stack ExchangeYou are correct, "peek" in the English sense of the word means "look, but do not touch."
However the JavaDoc states:
peek
Stream peek(Consumer action)
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.
Key words: "performing ... action" and "consumed". The JavaDoc is very clear that we should expect peek to have the ability to modify the stream.
However the JavaDoc also states:
API Note:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
This indicates that it is intended more for observing, e.g. logging elements in the stream.
What I take from all of this is that we can perform actions using the elements in the stream, but should avoid mutating elements in the stream. For example, go ahead and call methods on the objects, but try to avoid mutating operations on them.
At the very least, I would add a brief comment to your code along these lines:
// Note: this peek() call will modify the Things in the stream.
streamOfThings.peek(this::thingMutator).forEach(this::someConsumer);
Opinions differ on the usefulness of such comments, but I would use such a comment in this case.
It could be easily misinterpreted, so I would avoid using it like this. Probably the best option is to use a lambda function to merge the two actions you need into the forEach call. You may also want to consider returning a new object rather than mutating the existing one - it may be slightly less efficient, but it is likely to result in more readable code, and reduces the potential of accidentally using the modified list for another operation that should have received the original.
Videos
Hi There,
I am trying to learn Java 8 concepts and struck at one point while practicing peek operation. As per my knowledge peek is mainly for debugging purpose, where we want to see the elements as they flow past a certain point in a pipeline.
As per my expectation below code snippet should print 1 4 9 3. But its just printing 3, which is the result of count.
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list.stream().map(a -> a*a).peek(System.out::println).count());
When I try to user filter, it prints correct result which is 4 1
System.out.println(list.stream().map(a -> a*a).filter(a -> a%2==0).peek(System.out::println).count());
Is there something that I am missing here.
Thanks advance for your help
The important thing you have to understand is that streams are driven by the terminal operation. The terminal operation determines whether all elements have to be processed or any at all. So collect is an operation that processes each item, whereas findAny may stop processing items once it encountered a matching element.
And count() may not process any elements at all when it can determine the size of the stream without processing the items. Since this is an optimization not made in Java 8, but which will be in Java 9, there might be surprises when you switch to Java 9 and have code relying on count() processing all items. This is also connected to other implementation-dependent details, e.g. even in Java 9, the reference implementation will not be able to predict the size of an infinite stream source combined with limit while there is no fundamental limitation preventing such prediction.
Since peek allows “performing the provided action on each element as elements are consumed from the resulting stream”, it does not mandate processing of elements but will perform the action depending on what the terminal operation needs. This implies that you have to use it with great care if you need a particular processing, e.g. want to apply an action on all elements. It works if the terminal operation is guaranteed to process all items, but even then, you must be sure that not the next developer changes the terminal operation (or you forget that subtle aspect).
Further, while streams guarantee to maintain the encounter order for a certain combination of operations even for parallel streams, these guarantees do not apply to peek. When collecting into a list, the resulting list will have the right order for ordered parallel streams, but the peek action may get invoked in an arbitrary order and concurrently.
So the most useful thing you can do with peek is to find out whether a stream element has been processed which is exactly what the API documentation says:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
The key takeaway from this:
Don't use the API in an unintended way, even if it accomplishes your immediate goal. That approach may break in the future, and it is also unclear to future maintainers.
There is no harm in breaking this out to multiple operations, as they are distinct operations. There is harm in using the API in an unclear and unintended way, which may have ramifications if this particular behavior is modified in future versions of Java.
Using forEach on this operation would make it clear to the maintainer that there is an intended side effect on each element of accounts, and that you are performing some operation that can mutate it.
It's also more conventional in the sense that peek is an intermediate operation which doesn't operate on the entire collection until the terminal operation runs, but forEach is indeed a terminal operation. This way, you can make strong arguments around the behavior and the flow of your code as opposed to asking questions about if peek would behave the same as forEach does in this context.
accounts.forEach(a -> a.login());
List<Account> loggedInAccounts = accounts.stream()
.filter(Account::loggedIn)
.collect(Collectors.toList());
I'd like to be able to debug my operator results step-by-step a la Java's Stream::peek method. For those unfamiliar it looks something like...
someArrayOfStrings.stream()
.peek(element -> print(element))
.map(element -> element.append("!"))
.peek(element -> print(element))
...
and if the array is, e.g., ["hi", "i like swift"] then the output would be
hi i like swift hi! i like swift!
I've just started learning how to work with Combine so this question may be misguided or flawed. I know there's the Publishers.print operator (publisher?) but I couldn't seem to get it to do what I described above. It's possible I just didn't spend enough time with it.
So after a few hours of trudging through various Combine tutorials I decided to ask here before I lose any more of my sanity :).
EDIT: I seem to have found a solution with handleEvents(receiveOutput:). I'd now like to instead ask if this is best practice.