RFR: 8362958: Unnecessary copying / sorting in Streams using Comparator.naturalOrder() [v5]

Patrick Strawderman duke at openjdk.org
Tue Nov 11 18:33:29 UTC 2025


> When `Comparator.naturalOrder()` was explicitly supplied to a collection such as `TreeSet`, or passed into the `sorted` method of a stream, the sorted characteristic was not preserved, causing unnecessary buffering and duplicate sorting.
> 
> Example:
> 
> 
> TreeSet<Integer> sortedSet = new TreeSet<>(Comparator.naturalOrder());
> sortedSet.add(1);
> sortedSet.add(2);
> // SortedOps.OfRef.opWrapSink is not a no-op
> sortedSet.stream().sorted().forEach(System.out::println);
> 
> or
> 
> TreeSet<Integer> sortedSet = new TreeSet<>();
> sortedSet.add(1);
> sortedSet.add(2);
> // SortedOps.OfRef.opWrapSink is not a no-op
> sortedSet.stream().sorted(Comparator.naturalOrder()).forEach(System.out::println);
> 
> 
> This PR updates `SortedOps.makeRef` and `StreamOpFlag.fromCharacteristics` to handle the above cases and avoid the unnecessary sort step.

Patrick Strawderman has updated the pull request incrementally with one additional commit since the last revision:

  Fix SortOps.OfRef logic

-------------

Changes:
  - all: https://git.openjdk.org/jdk/pull/28226/files
  - new: https://git.openjdk.org/jdk/pull/28226/files/4c48f937..ea73382c

Webrevs:
 - full: https://webrevs.openjdk.org/?repo=jdk&pr=28226&range=04
 - incr: https://webrevs.openjdk.org/?repo=jdk&pr=28226&range=03-04

  Stats: 1 line in 1 file changed: 0 ins; 0 del; 1 mod
  Patch: https://git.openjdk.org/jdk/pull/28226.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/28226/head:pull/28226

PR: https://git.openjdk.org/jdk/pull/28226


More information about the core-libs-dev mailing list