![](/img/trans.png)
[英]Periodic action within Java stream / forEach when iterating a collection
[英]Java 8 Collection and stream/forEach
在使用Collection时,有没有理由在forEach调用之前专门插入流/并行流?
例:
Collection<Object> foo;
foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here
foo.parallelStream().forEach(); // Does this make a difference here?
谢谢
foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here
除非您需要像map或filter这样的流操作,否则它是无用的。
foo.parallelStream().forEach();
这会为计算机的每个逻辑核心生成一个新线程来计算项目。 想一想你是否使用这个功能,在大多数情况下它只能在长时间运行的操作上得到回报。
底线 :流可以在没有副作用的情况下使用,例如将类型A的集合映射到类型B,而不会改变A.循环很可能会改变流外的数据。
它做同样的工作,但范式是完全不同的。
Streams是函数式编程的一部分,它可以让您根据要做什么而不是如何进行思考。
我知道它可能听起来很抽象,但它确实很有意义。 所以基本上你专注于操作而不是迭代。 更不用说stream()为您提供了其他功能,如filter,map,reduce ...
而parallelStream将使您能够使用所有内核,这非常酷 - 您将拥有一个真正的多线程应用程序,而无需额外的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.