From 8f754ffe46bbe30bdfdf94a0027f3e3aaf48fa54 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 | 4 ++++ guava/src/com/google/common/collect/ImmutableSortedSet.java | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/guava/src/com/google/common/collect/CollectSpliterators.java b/guava/src/com/google/common/collect/CollectSpliterators.java index 7d0e82f203a8..b6bb16b8a93e 100644 --- a/guava/src/com/google/common/collect/CollectSpliterators.java +++ b/guava/src/com/google/common/collect/CollectSpliterators.java @@ -96,6 +96,10 @@ public int characteristics() { @CheckForNull public Comparator getComparator() { if (hasCharacteristics(Spliterator.SORTED)) { + if (Ordering.natural().equals(comparator) + || Comparator.naturalOrder().equals(comparator)) { + return null; + } return 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..034e9b9795c8 100644 --- a/guava/src/com/google/common/collect/ImmutableSortedSet.java +++ b/guava/src/com/google/common/collect/ImmutableSortedSet.java @@ -805,7 +805,12 @@ public boolean tryAdvance(Consumer action) { } @Override + @CheckForNull public Comparator getComparator() { + if (Ordering.natural().equals(comparator) + || Comparator.naturalOrder().equals(comparator)) { + return null; + } return comparator; } };