Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams: distinct() on a pre-sorted stream?

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.

like image 216
Jules Avatar asked Sep 12 '17 13:09

Jules


People also ask

How do I use distinct in stream?

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.

How does distinct work in Java stream?

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.

When performing operations on a stream will it affect the original stream?

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.

Is sorted () a terminal operation in Java?

The javadocs for both distinct() and sorted() say that they are "stateful intermediate operation".


1 Answers

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
like image 180
Eugene Avatar answered Sep 24 '22 04:09

Eugene