Setting a Stream as Unordered – Streams
Setting a Stream as Unordered
The unordered() intermediate operation does not actually reorder the elements in the stream to make them unordered. It just removes the ordered constraint on a stream if this constraint is set for the stream, indicating that stream operations can choose to ignore its encounter order. Indicating the stream to be unordered can improve the performance of some operations. For example, the limit(), skip(), and distinct() operations can improve performance when executed on unordered parallel streams, since they can process any elements by ignoring the encounter order. The removal of the ordered constraint can impact the performance of certain operations on parallel streams (p. 1015).
It clearly makes sense to call the unordered() method on an ordered stream only if the order is of no consequence in the final result. There is no method called ordered to impose an order on a stream. However, the sorted() intermediate operation can be used to enforce a sort order on the output stream.
In the stream pipeline below, the unordered() method clears the ordered constraint on the stream whose elements have the same order as in the data source—that is, the positional order in the list of CDs. The outcome of the execution shows that the titles in the result list are in the same order as they are in the data source; this is the same result one would get without the unordered() operation. It is up to the stream operation to take into consideration that the stream is unordered. The fact that the result list retains the order does not make it invalid. After all, since the stream is set as unordered, it indicates that ignoring the order is at the discretion of the stream operation.
//Query: Create a list with the first 2 Jazz CD titles.
List<String> first2JazzCDTitles = CD.cdList
.stream()
.unordered() // Don’t care about ordering.
.filter(CD::isJazz)
.limit(2)
.map(CD::title)
.toList(); // [Java Jam, Keep on Erasing]
The following method is inherited by the Stream<T> interface from its superinterface BaseStream. Analogous methods are also inherited by the IntStream, LongStream, and DoubleStream interfaces from the superinterface BaseStream.
Stream<T> unordered()
Returns an unordered sequential stream that has the same elements as this stream. The method returns itself if this stream is already unordered. The method can only indicate that the encounter order of this stream can be ignored, and an operation might not comply to this request.
This is an intermediate operation that does not change the stream size or the stream element type. It only indicates that the encounter order can be ignored.
Leave a Reply