Syntax
Stream<T> sorted();
Stream<T> sorted(Comparator<? super T> comparator);
🔹 How It Works
sorted()
(no arguments):
Sorts the stream elements in natural order, i.e., using theComparable
interface. This requires the elements to implementComparable
.sorted(Comparator)
(with comparator):
Sorts the stream using a customComparator
you provide.
🔹 Examples
✅ Natural Order
List<String> names = List.of("Charlie", "Alice", "Bob");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedNames); // [Alice, Bob, Charlie]
✅ Custom Order (e.g., by length)
List<String> names = List.of("Charlie", "Alice", "Bob");
List<String> sortedByLength = names.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
System.out.println(sortedByLength); // [Bob, Alice, Charlie]
🔹 Notes
sorted()
is intermediate, meaning it produces a new stream.- It performs a stable sort, preserving the order of equal elements.
- Sorting can be expensive, especially on large streams — use only when needed.
What is complexity of sorting ?
The time complexity of the sorted()
method in Java Streams depends on the underlying sorting algorithm, which is typically TimSort — the same as used in Arrays.sort()
and Collections.sort()
.
🔹 Time Complexity
Scenario | Complexity |
---|---|
Average case | O(n log n) |
Worst case | O(n log n) |
Best case (nearly sorted) | O(n) (due to TimSort optimizations) |
🔹 Why TimSort?
- Java uses TimSort (a hybrid of merge sort and insertion sort) for sorting objects.
- It is highly efficient for real-world data, especially if the data is partially sorted.
🔹 Space Complexity
- The space complexity is typically O(n) for object sorting.
Example
List<Integer> list = List.of(3, 5, 2, 4, 1);
List<Integer> sorted = list.stream().sorted().collect(Collectors.toList());
Under the hood:
- The elements are collected into an array.
- TimSort is applied.
- A new sorted stream is returned.