java - List.forEach 是用 Java 排序的吗?

标签 java java-8 java-stream

我用谷歌搜索了这个,也试图找到关于它的文档,但没有找到。

问题很简单。 我有一个 List 让我们说 foo。如果我这样做

foo.forEach(this::doSomething) 并为相同的 foo 再次使用相同的行,每次迭代的顺序是否相同?

如果是,那么 foo.stream().forEach() 呢?

最佳答案

forEachIterable 中定义,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/

相关文章:

java - 如何使用流加入非字符串对象列表

java - 如何比较两个 map 并检索两个 map 中出现的值的键?

java - 如何从 Java 中的动态源创建对象流?

java - CollectionUtils.isNotEmpty 和 In Place 检查之间的性能差异

java - 使用 Java 存储 SHA2 密码

java - 在stream和noneMatch方面遇到了一些真正的麻烦

java - 如何在调用另一个方法时使用lambda表达式将方法作为参数传递?

java - 方法 .toArray(IntFunction<A[]> Generator) 如何知道新数组的大小

java - 准备一组可以传递给 java 中的函数的参数

java - 如何从 Saxon 的扩展函数返回文档节点?