Ordering
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered, such as BaseStream.unordered(). Further, some terminal operations may ignore encounter order, such as forEach().
HashSet
?unordered
intermidiate operation on each stream that will be computed in parallel?Besides the HashSet
and HashMap
’s collection views, Stream.generate()
will generate an unordered stream.
Needless to say, streams generated by a Random
are unordered too. Also, Stream.empty()
does not report to have an encounter order, but that has not much consequences…
If you know that you don’t need the Stream to maintain the encounter order, it’s a good practice to use unordered()
—even if it doesn’t improve the performance, as with most operations in the current implementation, it doesn’t harm and will document that you don’t care for the order. That does not only apply to parallel streams, some operations, like distinct()
, may benefit from unorderedness even in the sequential case.
In some cases, choosing the right terminal operation, like findAny()
instead of findFirst()
documents that intent more concise and will also have a higher impact on the performance, given the current implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With