Skip to content

Conversation

@nickita-khylkouski
Copy link

@nickita-khylkouski nickita-khylkouski commented Jan 26, 2026

Summary

  • Return null from Spliterator.getComparator() when comparator is natural ordering
  • Check for both Ordering.natural() and Comparator.naturalOrder() (both singletons)
  • Apply fix to ImmutableSortedSet.spliterator() and CollectSpliterators.indexed()
  • Add unit tests for the new behavior

Motivation

Per the Spliterator.getComparator() contract, null should be returned to indicate natural ordering. The JDK stream implementation clears the SORTED flag when getComparator() returns non-null, which prevents the sorted() optimization.

This causes unnecessary sorting when calling stream().sorted() on naturally-ordered ImmutableSortedSet:

ImmutableSortedSet<Integer> sortedSet = ImmutableSortedSet.of(1, 2, 3, 4);
// sorted() should be a no-op, but wasn't because getComparator() returned Ordering.natural()
sortedSet.stream().sorted().collect(Collectors.toList());

Fixes #6187

Testing

Added 3 unit tests to ImmutableSortedSetTest:

  • testSpliteratorComparator_naturalOrdering - verifies getComparator() returns null for natural ordering
  • testSpliteratorComparator_customComparator - verifies custom comparator is returned
  • testAsListSpliteratorComparator_naturalOrdering - verifies asList().spliterator() also returns null

Also verified locally that stream sorted() optimization now works correctly.

…ering

Per the Spliterator.getComparator() contract, return null to indicate
natural ordering. This enables stream optimizations where sorted()
becomes a no-op for already-sorted collections using natural ordering.

Previously, ImmutableSortedSet and CollectSpliterators returned
Ordering.natural() instead of null, which caused the JDK stream
implementation to clear the SORTED flag and re-sort unnecessarily.

The fix checks for both Ordering.natural() and Comparator.naturalOrder()
using reference equality (both are singletons).

Fixes google#6187
@nickita-khylkouski nickita-khylkouski force-pushed the fix-sorted-spliterator-natural-order branch from d90367a to 843e726 Compare January 26, 2026 19:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Spliterators for sorted collections cause inefficient stream operations when natural ordering is used

1 participant