Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.map vs .peek - Intellij suggestions [duplicate]

Tags:

java

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?

like image 541
Dargenn Avatar asked Aug 02 '18 07:08

Dargenn


2 Answers

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.

like image 55
Coder-Man Avatar answered Oct 26 '22 12:10

Coder-Man


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.

like image 36
Dawid Kubicki Avatar answered Oct 26 '22 11:10

Dawid Kubicki