-5

If an intermediate operation consumes some elements of the stream and peek() is used after, but there is no terminal operation, surely peek() should still produce some output?

ICTOAUN
  • 71
  • 4

1 Answers1

1

If an intermediate operation consumes some elements of the stream

This is correct.

However, no intermediate operation ever consumes elements of a stream, so, you know. Technically correct at best.

In this code:

someCollection.stream().map(stuff).flatMap(otherStuff).filter(whatever).limit(20);

nothing is going to happen. Each 'element', such as .map(stuff), is simply registering an IF data is pushed through this stream, push it through this code. It does not consume anything. There is no terminal here, so none of the supplied code is ever run.

Only terminal operations cause data to flow, and in so doing, all that data passes through all those intermediates, and not before.

seek is thus not special. It's at the same 'level' of map, flatMap, filter, limit, and all the other intermediates: Does not cause consumption, is merely in there as part of the pipeline.

Imagine a water pipe. someCollection.stream() is the source of the water, all the stuff in the middle is pipe, and the 'terminal' at the end (be it max, collect, findAny, foreach, etc) is the faucet.

If you never turn the faucet on, it doesn't matter how many fancy little fanblades and other water-powered toys you put in the line. None of them will do anything.

rzwitserloot
  • 65,603
  • 5
  • 38
  • 52