Java 8 Collection and stream/forEach

て烟熏妆下的殇ゞ 提交于 2019-12-07 13:30:35

问题


Is there any reason to specifically insert a stream/parallel stream before a forEach call when using a Collection?

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


回答1:


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.

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.




回答2:


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.

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...

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.



来源:https://stackoverflow.com/questions/39881207/java-8-collection-and-stream-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!