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

Jules :

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.

Eugene :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440351&siteId=1