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 Oct 18, 2022
1 parent e452209 commit 8f754ff
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
4 changes: 4 additions & 0 deletions guava/src/com/google/common/collect/CollectSpliterators.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ public int characteristics() {
@CheckForNull
public Comparator<? super T> getComparator() {
if (hasCharacteristics(Spliterator.SORTED)) {
if (Ordering.natural().equals(comparator)
|| Comparator.naturalOrder().equals(comparator)) {
return null;
}
return comparator;
} else {
throw new IllegalStateException();
Expand Down
5 changes: 5 additions & 0 deletions guava/src/com/google/common/collect/ImmutableSortedSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,12 @@ public boolean tryAdvance(Consumer<? super E> action) {
}

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

0 comments on commit 8f754ff

Please sign in to comment.