简体   繁体   English

Java 8 Collection和stream / forEach

[英]Java 8 Collection and stream/forEach

Is there any reason to specifically insert a stream/parallel stream before a forEach call when using a Collection? 在使用Collection时,有没有理由在forEach调用之前专门插入流/并行流?

Example: 例:

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?

Thanks 谢谢

foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here

It is useless unless you need stream operations like map or filter. 除非您需要像map或filter这样的流操作,否则它是无用的。

foo.parallelStream().forEach();

This spawns a new thread for every logical core of your computer to compute the items. 这会为计算机的每个逻辑核心生成一个新线程来计算项目。 Think twice about whether or not you use this feature, in most cases it only pays off on long running operations. 想一想你是否使用这个功能,在大多数情况下它只能在长时间运行的操作上得到回报。

Bottom line : Streams really shine when they can be used without side-effects, like mapping collection of type A to type B, without altering A. Loops most likely will alter data outside the stream. 底线 :流可以在没有副作用的情况下使用,例如将类型A的集合映射到类型B,而不会改变A.循环很可能会改变流外的数据。

It does the same job, however the paradigm is completely different. 它做同样的工作,但范式是完全不同的。

Streams are a part of functional programming which lets you think in terms of what to do and not how. Streams是函数式编程的一部分,它可以让您根据要做什么而不是如何进行思考。

I know it may sound abstract, but it really makes sense. 我知道它可能听起来很抽象,但它确实很有意义。 So basically you focus on operations and not iterations. 所以基本上你专注于操作而不是迭代。 Not to mention that stream() offers you additional functionality like filter, map, reduce... 更不用说stream()为您提供了其他功能,如filter,map,reduce ...

And parallelStream will enable you to use all your cores, which is pretty cool - you will have a truly multithreaded application without a single extra line of code. 而parallelStream将使您能够使用所有内核,这非常酷 - 您将拥有一个真正的多线程应用程序,而无需额外的代码。

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

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