collection.stream().map(x -> {
if(condition) {
x.setY(true);
}
return x;
}).collect(Collectors.toList()));
I have a collection, and I want to set something in x
variable when a certain condition is met. I'm doing it like it's shown in the code above. It does its job, and works. However, IntelliJ suggests that I swap .map
with .peek
. So the code would look like:
collection.stream().peek(x -> {
if(condition) {
x.setY(true);
}
}).collect(Collectors.toList()));
It's one line shorter, but from what I read on peek documentation:
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:
So, is IntelliJ's suggestion misleading?
Example:
If you use peek()
with count()
in java 8, peek()
will work, but if you use it in java 9, it won't unless you have filter()
, because count()
in java 9 doesn't go over all the elements.
You should prefer forEach
to peek
.
List<Integer> l = new ArrayList<>(Arrays.asList(1,2,3));
long c = l.stream().peek(System.out::println).count();
System.out.println(c);
Try the code above in java 8 and 9 and see the difference. My point is that you should follow what the API documentation says and use it accordingly.
No is not misleading. 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.
The JavaDoc is very clear that peek have the ability to modify the stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With