Thursday, 2 May 2024

Stream.sorted() - For unordered streams, no stability guarantees are made.

So I was writing code, and I had to sort a stream, because originally I had a Set, and everyone knows Sets are unordered by default.

But my eye fell on the javadoc on .sorted(). To be more specific:

For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

And the sentence kind of made me nervous.

Example

An example of an unstable sort is visible in the unit test below. The unit test will sometimes pass and sometimes fail.

The reason for this is that Ken Thompson and Simon Thompson are equivalent in the sorting and, as it is an unsorted stream to begin with, its order can change between program runs.

Something to keep in mind.

References

Oracle Javadoc - Stream (Java SE 21 & JDK 21)
https://docs.oracle.com/en%2Fjava%2Fjavase%2F21%2Fdocs%2Fapi%2F%2F/java.base/java/util/stream/Stream.html#sorted()

No comments:

Post a Comment