Java 8 Collection和stream / forEach [英] Java 8 Collection and stream/forEach

查看:200
本文介绍了Java 8 Collection和stream / forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Collection时,有没有理由在forEach调用之前专门插入流/并行流?



示例:

  Collection< Object> FOO; 
foo.forEach(); //遍历foo
foo.stream()。forEach(); //流是否有所不同
foo.parallelStream()。forEach(); //这会有所不同吗?

谢谢

解决方案

  foo.forEach(); //遍历foo 
foo.stream()。forEach(); //流是否有所不同

除非您需要像map或filter这样的流操作,否则它是无用的。

  foo.parallelStream()。forEach(); 

这会为计算机的每个逻辑核心生成一个新线程来计算项目。想一想你是否使用这个功能,在大多数情况下它只能在长时间运行中得到回报。



底线:Streams真的当它们可以在没有副作用的情况下使用时发光,比如将A类型的集合映射到B类,而不改变A.循环很可能会改变流外的数据。


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

解决方案

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.

这篇关于Java 8 Collection和stream / forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆