Java 8 Stream 中的 forEach 与 forEachOrdered [英] forEach vs forEachOrdered in Java 8 Stream
问题描述
我知道这些方法的执行顺序不同,但在我的所有测试中,我无法实现不同的顺序执行.
I understand that these methods differ the order of execution but in all my test I cannot achieve different order execution.
示例:
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
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));
第二行总是输出
Output:AAA
Output:BBB
Output:CCC
而第一个没有保证,因为没有保留订单.forEachOrdered
将按照其源指定的顺序处理流的元素,无论流是顺序的还是并行的.
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.
引用自 forEach
Javadoc:
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.
当 forEachOrdered
Javadoc 声明(强调我的):
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.
这篇关于Java 8 Stream 中的 forEach 与 forEachOrdered的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!