<分区>
TL;DR; 我正在寻找一个可以查找特定中间操作或终端操作的地方。在哪里可以找到此类文档?
编辑 这不是How to ensure order of processing in java8 streams? 的副本,因为该问题没有提供完整的操作列表。
背景
Whether or not a stream has an encounter order depends on the source and the intermediate operations
在 this excellent stackoverflow answer 中重复
In order to ensure maintenance of ordering throughout an entire stream operation, you have to study the documentation of the stream’s source, all intermediate operations and the terminal operation for whether they maintain the order or not (or whether the source has an ordering in the first place).
这一切都很好,但我应该查看哪个文档? the package documentation在示例中提到 map
保证排序,但它没有详尽的列表。 javadoc for the Stream class记录一些中间操作,但不是全部。
以map
为例:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
This is an intermediate operation.
Returns a stream consisting of the elements of this stream that match the given predicate.
This is an intermediate operation.
这些都没有描述它们是否保留顺序。
Actually every intermediate operation preserves an order by default. The only exceptions are:
- unordered() which removes the ordering constraint.
- sorted() which changes the order.
When it's not explicitly specified, you can assume that operation keeps the order. Even distinct() keeps the order, though it adds much complexity for parallel stream.
但是是否有任何官方文档来支持这一点?
加分 😉
实际上有两个单独的排序问题。
- 操作的输出是否保持与输入相同的顺序?
- 操作是否按顺序在每个元素上执行。
例如,并行 map
操作可以以任意顺序遍历所有元素(违反 2.),但仍保持返回流中的顺序(遵守 1.)