manish2aug
manish2aug

Reputation: 123

Stream peek() method behaviour

List<Integer> nums = Arrays.asList(1,2,3,4,5,6);
long result = nums
        .stream()
        .peek(System.out::print)
        .map(n->n*n)
        .filter(n->n>20)
        .peek(System.out::print)
        .count();
System.out.println(result);     

Why shouldn't it print 12345625362 instead of 1234525362?

Upvotes: 2

Views: 460

Answers (2)

GBlodgett
GBlodgett

Reputation: 12819

If we add spaces inside the println in peek we can get a better idea of why this happens:

long result2 = nums.stream()
                   .peek(e -> System.out.print(e + " "))
                   .map(n->n*n)
                   .filter(n->n>20)
                   .peek(e -> System.out.print(e + " "))
                   .count();

This outputs:

1 2 3 4 5 25 6 36 

As you can see 1 goes through, is printed out, does not pass the filter, and is thus the square is not printed. The same is true for 2, 3, and 4. Then 5 goes through, and is printed. It passes the filter, so 25 is printed. So far we have :

1 2 3 4 5 25

Then six passes through in a similar fashion and we are left with

1 2 3 4 5 25 6 36 

And then System.out.println(result); is printed. Since the last call was to print and not println it is printed on the same line, so a 2 is appended. If we take back out the spaces this yields:

12345256362

Which is the result

Upvotes: 5

luk2302
luk2302

Reputation: 57124

All stream operations are first applied to 1, first peek / print, then map and then filter, removing the element. Same exact thing happens to 2, 3 and 4. The output afterwards is 1 2 3 4.

Then for 5 we peek / print, then map, filter leaving the element in tact and then peek / print the squared number. Output 5 25

Same thing for 6. Output: 6 36.

All together 1234 525 636 -> 1234525636

And then a final 2 for the count.

Upvotes: 1

Related Questions