我用谷歌搜索了这个,也试图找到关于它的文档,但没有找到。
问题很简单。
我有一个 List
让我们说 foo。如果我这样做
foo.forEach(this::doSomething)
并为相同的 foo
再次使用相同的行,每次迭代的顺序是否相同?
如果是,那么 foo.stream().forEach()
呢?
最佳答案
forEach
在 Iterable
中定义,Javadoc 说:
Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified).
现在 List.iterator()
说:
Returns an iterator over the elements in this list in proper sequence.
因此默认情况下,您应该期望 forEach
以正确的顺序枚举元素 - 除非列表实现具有不同的迭代器实现。
根据 Stream.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.
但是还有Stream.forEachOrdered
:
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 - List.forEach 是用 Java 排序的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226231/