I think this is a bug in Oracle JDK (1.8.0_45).
When you create a stream sorted using natural order with Stream#sorted() , it internally transfers the stream to SortedOps.OfRef using the following constructor:
OfRef(AbstractPipeline<?, T, ?> upstream) { super(upstream, StreamShape.REFERENCE, StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED); ...
When you give a custom Comparator with Stream#sorted(Comparator) , it does the same, but uses the following constructor instead:
OfRef(AbstractPipeline<?, T, ?> upstream, Comparator<? super T> comparator) { super(upstream, StreamShape.REFERENCE, StreamOpFlag.IS_ORDERED | StreamOpFlag.NOT_SORTED); ...
StreamOpFlag.NOT_SORTED intended to clear the SORTED flag, if it was set earlier. This means that after this operation, the sorted stream will become an unordered stream.
I think that this could be used incorrectly instead of StreamOpFlag.IS_SORTED , and the call to super() should use the same parameters as in the first constructor.
I could not find the corresponding problem in the Java Bug System, but.
source share