Integrated: 8362958: Unnecessary copying / sorting in Streams using Comparator.naturalOrder()
Patrick Strawderman
duke at openjdk.org
Tue Nov 25 10:16:40 UTC 2025
On Tue, 11 Nov 2025 02:43:14 GMT, Patrick Strawderman <duke at openjdk.org> wrote:
> 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.
This pull request has now been integrated.
Changeset: 67ef81eb
Author: Patrick Strawderman <pstrawderman at netflix.com>
Committer: Viktor Klang <vklang at openjdk.org>
URL: https://git.openjdk.org/jdk/commit/67ef81eb78b28e5dcdf91785b476dfd0858cbd16
Stats: 46 lines in 4 files changed: 16 ins; 4 del; 26 mod
8362958: Unnecessary copying / sorting in Streams using Comparator.naturalOrder()
Reviewed-by: vklang, liach
-------------
PR: https://git.openjdk.org/jdk/pull/28226
More information about the core-libs-dev
mailing list