As discussed in this question, the implementation of distinct()
is able to use a more efficient algorithm when the stream it operates on is known by the runtime to be sorted. How can we achieve a similar result if we know that the stream is sorted (e.g. because it came from an externally pre-sorted data source, such as an SQL query with an order by
clause) but isn't flagged as such? There's an unordered()
operation that removes the ordering flags, but as far as I can see no way of telling the system that the data has been ordered externally.
distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not necessarily stable and can change.
Java Stream distinct() Method It means that the element occurring first will be present in the distinct elements stream. If the stream is unordered, then the resulting stream elements can be in any order. Stream distinct() is a stateful intermediate operation.
A stream can be composed of multiple functions that create a pipeline that data that flows through. This data cannot be mutated. That is to say the original data structure doesn't change. However the data can be transformed and later stored in another data structure or perhaps consumed by another operation.
The javadocs for both distinct() and sorted() say that they are "stateful intermediate operation".
You could create your spliterator around an existing collection for example:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Spliterator<Integer> sp = Spliterators.spliterator(list, Spliterator.SORTED);
System.out.println(sp.hasCharacteristics(Spliterator.SORTED)); // true
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