Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encounter order collections - best practice & example

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().

  1. Are there any other types that does not have the encounter order property but HashSet?
  2. In case I'm not intersted in keeping the exsisting order or any sort of sorting, is it considered to be best practice by explicitly calling to unordered intermidiate operation on each stream that will be computed in parallel?
like image 903
Stav Alfi Avatar asked Dec 18 '22 07:12

Stav Alfi


1 Answers

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.

like image 146
Holger Avatar answered Jan 08 '23 14:01

Holger