I have read that the streams are evaluated lazily in the pipeline. It is not executed unless the terminal opertion is invoked on the expression. But, what are the benefits of this lazy evaluation of the expressions? Can someone please explain with some examples
Asked
Active
Viewed 1,092 times
1
-
5_pipeline_, _terminal operation_ - you are referring to `Stream`? – LuCio Sep 24 '18 at 11:39
-
[What are the advantages of lazy evaluation?](https://stackoverflow.com/questions/2151226/what-are-the-advantages-of-lazy-evaluation) – jaco0646 Sep 24 '18 at 18:59
1 Answers
2
Lazy evaluation of stream pipelines in Java has nothing to do with lambdas.
All but the last stations in a stream pipeline are evaluated only when the last station asks for more data. When the last station pulls the one second from the last, that one pulls from the one before it and so forth until finally the reqeust for the new data makes all the way to supplier. The supplier then provides next one value which gets propagated back (actually forth) through the pipeline to the last stage (a collector or a forEach) and the cycle repeats.
This approach does not require the pipeline implementation to over-produce and/or buffer anything. This is great for CPU and memory footprint, which is usually a great bias for Java applications.
Example:
Stream
.generate(new Random(42)::nextLong) // <-- supplies the next random number every time the next station pulls it
.limit(5) // <-- pulls from the generator when is pulled itself
// terminates the pipeline after 5 pulls
.collect(toList()); // <-- pulls data from the pipeline into the list

bobah
- 18,364
- 2
- 37
- 70