gpt4 book ai didi

java - Java 8 Stream 中的 forEach 与 forEachOrdered

转载 作者:IT老高 更新时间:2023-10-28 13:52:49 26 4
gpt4 key购买 nike

我了解这些方法的执行顺序不同,但在我的所有测试中,我无法实现不同的执行顺序。

例子:

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

请提供两种方法产生不同输出的示例。

最佳答案

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 将按照其源指定的顺序处理流的元素,而不管流是顺序的还是并行的。

引自 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 状态(强调我的):

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 - Java 8 Stream 中的 forEach 与 forEachOrdered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32797579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com