CKTIS / Java
Stream.sorted: practical reference
Stream.sorted: practical reference: Stream.sorted is a stateful intermediate operation using natural order or a supplied Comparator; sorting is stable for an ordered stream.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.sorted(...)Stream.sorted is a stateful intermediate operation using natural order or a supplied Comparator; sorting is stable for an ordered stream.
Use sorted before a terminal ranking or presentation step; provide a Comparator when the element type lacks the intended natural order.
The operation buffers elements and may use substantial memory, especially in parallel; the Comparator must be stateless, non-interfering, and define the intended order.
Natural sorting may throw ClassCastException only when the terminal operation runs if elements are not Comparable; an unordered stream has no stability guarantee.
Natural sorted orders the 3, 1, 2 input ascending; the toList result and exact stdout [1, 2, 3] show the post-sort encounter order.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of(3, 1, 2).sorted().toList();
System.out.println(result);
}
}
Result
[1, 2, 3]
Natural sorted orders the 3, 1, 2 input ascending; the toList result and exact stdout [1, 2, 3] show the post-sort encounter order.