Java 8 Collection and stream/forEach

白昼怎懂夜的黑 提交于 2019-12-05 23:12:07
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.

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.

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