From aae7c2417597a2b0607252742def6130c7f544d9 Mon Sep 17 00:00:00 2001 From: Patrick Strawderman Date: Wed, 28 Sep 2022 13:19:50 -0700 Subject: [PATCH] Fix Spliterator implementations for sorted collections 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. --- guava/src/com/google/common/collect/CollectSpliterators.java | 2 +- guava/src/com/google/common/collect/ImmutableSortedSet.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/guava/src/com/google/common/collect/CollectSpliterators.java b/guava/src/com/google/common/collect/CollectSpliterators.java index 7d0e82f203a8..db6dce694c0e 100644 --- a/guava/src/com/google/common/collect/CollectSpliterators.java +++ b/guava/src/com/google/common/collect/CollectSpliterators.java @@ -96,7 +96,7 @@ public int characteristics() { @CheckForNull public Comparator getComparator() { if (hasCharacteristics(Spliterator.SORTED)) { - return comparator; + return Ordering.natural().equals(comparator) ? null : comparator; } else { throw new IllegalStateException(); } diff --git a/guava/src/com/google/common/collect/ImmutableSortedSet.java b/guava/src/com/google/common/collect/ImmutableSortedSet.java index 20d007271298..ed3554193838 100644 --- a/guava/src/com/google/common/collect/ImmutableSortedSet.java +++ b/guava/src/com/google/common/collect/ImmutableSortedSet.java @@ -805,8 +805,9 @@ public boolean tryAdvance(Consumer action) { } @Override + @CheckForNull public Comparator getComparator() { - return comparator; + return Ordering.natural().equals(comparator) ? null : comparator; } }; }