9

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.

Jules
  • 14,841
  • 9
  • 83
  • 130

1 Answers1

4

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
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • The streams I'm using are produced by a third party library, so I don't create spliterators myself at all. I guess I *could* use some kind of proxy spliterator, which might work. – Jules Sep 12 '17 at 21:26
  • Yeah, a wrapping spliterator reporting different characteristics seems to be the only solution. – Holger Sep 12 '17 at 22:12