Java.Java8.What is the sorted() method for in streams?

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 the Comparable interface. This requires the elements to implement Comparable.
  • sorted(Comparator) (with comparator):
    Sorts the stream using a custom Comparator 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

ScenarioComplexity
Average caseO(n log n)
Worst caseO(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:

  1. The elements are collected into an array.
  2. TimSort is applied.
  3. A new sorted stream is returned.

This entry was posted in Без рубрики. Bookmark the permalink.