The stream().sorted() method in Java is used to sort the elements of a stream. It offers two ways to achieve this:
Natural Order:
If the stream elements implement the Comparable interface, sorted() sorts them based on their natural order (e.g., integers in ascending order, strings in lexicographical order).
Custom Comparator:
You can provide a custom Comparator to define a specific sorting order. This allows you to sort elements based on any criteria you need (e.g., by length, by a specific field, etc.).
Key Points:
Intermediate Operation: sorted() is an intermediate operation, meaning it doesn’t immediately modify the original stream. It returns a new stream with the sorted elements.
Lazy Evaluation: The sorting operation is deferred until a terminal operation (like collect(), forEach()) is called on the stream.
Stability: For ordered streams, the sorted() method is stable, meaning that elements with equal values maintain their original relative order.
By using stream().sorted(), you can efficiently sort elements within a stream in various ways, making it a valuable tool for data manipulation in Java.