Skip to content

Commit

Permalink
Fix Spliterator implementations for sorted collections
Browse files Browse the repository at this point in the history
Spliterators returned by CollectSpliterators.indexed and ImmutableSortedSet.spliterator
violated the Spliterator API by not returning null in getComparator when the source
items are naturally sorted. The effect was that sort operations on Streams backed by
these Spliterators were not optimized away, resulting in additional unnecessary sorting.

Fixes #6187.
  • Loading branch information
kilink committed Sep 28, 2022
1 parent e452209 commit aae7c24
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public int characteristics() {
@CheckForNull
public Comparator<? super T> getComparator() {
if (hasCharacteristics(Spliterator.SORTED)) {
return comparator;
return Ordering.natural().equals(comparator) ? null : comparator;
} else {
throw new IllegalStateException();
}
Expand Down
3 changes: 2 additions & 1 deletion guava/src/com/google/common/collect/ImmutableSortedSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -805,8 +805,9 @@ public boolean tryAdvance(Consumer<? super E> action) {
}

@Override
@CheckForNull
public Comparator<? super E> getComparator() {
return comparator;
return Ordering.natural().equals(comparator) ? null : comparator;
}
};
}
Expand Down

0 comments on commit aae7c24

Please sign in to comment.