forEach vs forEach在Java 8 Stream中订购 [英] forEach vs forEachOrdered in Java 8 Stream

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

问题描述

我知道这些方法不同于执行顺序,但是在我所有的测试中我都无法实现不同的命令执行。



示例:

  System.out.println(forEach Demo); 
Stream.of(AAA,BBB,CCC)。forEach(s-> System.out.println(Output:+ s));
System.out.println(forEachOrdered Demo);
Stream.of(AAA,BBB,CCC)。forEachOrdered(s-> System.out.println(Output:+ s));

输出:

  forEach Demo 
输出:AAA
输出:BBB
输出:CCC
forEachOrdered Demo
输出:AAA
输出:BBB
输出:CCC

请提供两种方法产生不同输出的例子。 (AAA,BBB,CCC)。parallel()。b $ b

解决方案

 的forEach(S->的System.out.println( 输出: + S)); (AAA,BBB,CCC)。parallel()。forEachOrdered(s-> System.out.println(Output:+ s)); 

第二行总是输出

输出:AAA 
输出:BBB
输出:CCC

而第一个不保证,因为订单不被保留。 forEachOrdered 将按照源代码指定的顺序处理流的元素,而不管流是顺序还是并行。



forEach Javadoc:


这个操作的行为是明确的不确定的。对于并行流管线,这个操作并不能保证尊重流的遇到顺序,因为这样做会牺牲并行的好处。



<当 forEachOrdered Javadoc状态(强调我的):

lockquote

执行如果该流具有定义的遭遇顺序,则该流的每个元素(在流的遇到顺序中)。


I understand that these methods differ the order of execution but in all my test I cannot achieve different order execution.

Example:

System.out.println("forEach Demo");
Stream.of("AAA","BBB","CCC").forEach(s->System.out.println("Output:"+s));
System.out.println("forEachOrdered Demo");
Stream.of("AAA","BBB","CCC").forEachOrdered(s->System.out.println("Output:"+s));

Output:

forEach Demo
Output:AAA
Output:BBB
Output:CCC
forEachOrdered Demo
Output:AAA
Output:BBB
Output:CCC

Please provide examples when 2 methods will produce different outputs.

解决方案

Stream.of("AAA","BBB","CCC").parallel().forEach(s->System.out.println("Output:"+s));
Stream.of("AAA","BBB","CCC").parallel().forEachOrdered(s->System.out.println("Output:"+s));

The second line will always output

Output:AAA
Output:BBB
Output:CCC

whereas the first one is not guaranted since the order is not kept. forEachOrdered will processes the elements of the stream in the order specified by its source, regardless of whether the stream is sequential or parallel.

Quoting from forEach Javadoc:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

When the forEachOrdered Javadoc states (emphasis mine):

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

这篇关于forEach vs forEach在Java 8 Stream中订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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