Which operations preserve order [duplicate]

2019-02-01 23:08发布

问题:

This question already has an answer here:

  • How to ensure order of processing in java8 streams? 2 answers

TL;DR; I am looking for a place where I can lookup whether a certain intermediate or terminal operation. Where can I find such documentation?

Edit This is not a duplicate of How to ensure order of processing in java8 streams?, since that question does not provide a comprehensive list of operations.

Background

The the package documentation says:

Whether or not a stream has an encounter order depends on the source and the intermediate operations

Which is repeated in 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).

That is all well and good, but which documentation should I look at? The the package documentation mentions in an example that map guarantees ordering, but it doesn't have a exhaustive list. The javadoc for the Stream class documents some intermediate operations, but not all. Take for example map:

Returns a stream consisting of the results of applying the given function to the elements of this stream.

This is an intermediate operation.

or filter

Returns a stream consisting of the elements of this stream that match the given predicate.

This is an intermediate operation.

None of these describe whether they preserve ordering.

This stackoverflow answer claims:

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.

but is there any official documentation to back that up?

Extra credit