Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

In what order do the elements of a stream become available?

The order in which a stream’s elements are made available to the “downstream” operation (the one that ends it) depends on its source. There are two main possibilities:

  • The source has an encounter order : this is the order in which the source itself makes its elements available. For example, the encounter order for an array is defined by the ordering of its elements; for an ordered collection like a List or a NavigableMap, by its iteration order; for a generator function by the function itself, and so on.
  • The source has no encounter order. For example, a Set, which is inherently unordered, has none.

The operation that terminates a stream may be an intermediate operation feeding its results into the next component stream of the pipeline, or a terminal operation ending the pipeline as a whole. Each intermediate or terminal operation acts on the encounter order in one of three ways:

  • An encounter order may be imposed on the output. For example, the output of sorted always has one;
  • It may preserve an existing encounter order if there is one. For example, filter may drop some elements from the stream, but the order of the surviving elements is unchanged;
  • It may destroy an existing encounter order. For example, the new encounter order imposed by sorted will replace any existing one.

Collectors preserve encounter order if they are accumulating into a container that itself has an encounter order. For example, collection into an array will place the elements into the array in the encounter order of the stream. This is an example of a terminal operation that requires an ordering on its input. Such operations—non-commutative reductions are another example—will assign an arbitrary order to an unordered stream.

The explanation above applies to forEachOrdered, but not to any other operation that works by side-effect (e.g. forEach and peek). For these operations, no guarantee is made about execution order of side-effects for any stream, whether ordered or unordered.

Sequential and parallel streams have the same properties with respect to ordering.

The unordered method may be applied to a stream to indicate to the implementation that a stream’s encounter order can be disregarded. Parallel streams may perform some operations more efficiently when they do not have to respect the ordering of stream elements.

This name is not very descriptive. Encounter order can best be thought of as the spatial ordering of elements in a collection or other source.