简体   繁体   English

Java中流的延迟评估的优势

[英]Advantage of lazy evaluation of streams in java

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 有人可以举例说明吗

Lazy evaluation of stream pipelines in Java has nothing to do with lambdas. Java 中流管道的延迟评估与lambda无关。

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. 然后,供应商提供下一个值,该值通过管道传播回(实际上是向前传播)到最后一个阶段(收集器或forEach),并且循环重复进行。

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. 这对于CPU和内存占用量非常有用,通常对于Java应用程序来说是一个很大的偏差。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM