Video in progress

Strong Middle 🌊 Streams and lambdas

Is sorted() in a stream stable? Is the original order of equal elements preserved?

On an ordered stream, yes: the Javadoc guarantees it, in parallel mode too. On an unordered stream (from a HashSet or after unordered()) there's no stability guarantee. Because of this property you can build a multi-level order with two sorts in a row or with thenComparing.

📖 Answer

Stability means that elements found to be equal keep their relative order from before the sort.

record Task(String name, int priority) {}

List<Task> tasks = List.of(
        new Task("deploy", 2), new Task("backup", 1),
        new Task("report", 2), new Task("cleanup", 1));

tasks.stream()
     .sorted(Comparator.comparingInt(Task::priority))
     .toList();
// [backup, cleanup, deploy, report]: original order within the same priority

Where this matters in practice: the list already came ordered by creation time, now you sort by priority, and within the same priority the older ones must stay first. A stable sort gives you that for free.

Where there's no guarantee:

new HashSet<>(tasks).stream().sorted(...)   // the source is unordered: there's no "original order"
tasks.stream().unordered().sorted(...)      // the guarantee was removed

Under the hood, Arrays.sort (TimSort) is used for objects, and it is stable. For primitives (IntStream.sorted()) a different algorithm is used, but you can't tell equal ints apart anyway, so it doesn't matter.

One piece of advice: relying on stability and sorting twice, "first by name, then by priority", works, but it's confusing to read. A single comparator is clearer:

.sorted(Comparator.comparingInt(Task::priority).thenComparing(Task::name))