Course contentsShow
← Java
Lesson 1484 of 2,87032. Streams API: Intermediate OperationsFree lesson

Sorting Before limit

Why sorted must complete before limit takes effect, and the performance implications of this ordering.

Sorting Before limit

You'll learn why the order of sorted() and limit() in your stream pipeline dramatically affects both correctness and performance.

Why Sorted Must Complete Before Limit

When you place sorted() before limit() in a pipeline, the sorting operation must examine and order the entire stream before limit() can select the top N elements. This is unavoidable because:

  • To know which elements are the "first 3" after sorting, you must sort everything first
  • sorted() is a stateful operation that buffers all elements internally
  • Unlike filter or map, sorting can't produce output until it's seen all inputs

The Performance Impact

Consider finding the 5 smallest numbers from a million-element stream:

stream()
    .sorted()           // Processes all 1,000,000 elements
    .limit(5)           // Then takes first 5

Even though you only want 5 results, sorted() must:

  1. Consume the entire stream (1 million elements)
  2. Sort them all (expensive: O(n log n))
  3. Only then can limit() take the first 5

The Analogy: Imagine you need the 3 shortest pencils from a box of 1,000. If you fully sort all pencils by length first, you're doing far more work than necessary. (A partial sort or priority queue would be smarter, but Stream's sorted() doesn't optimize this automatically.)

When This Pattern Is Correct

This ordering is necessary when you want "top N after sorting":

employees.stream()
    .sorted(Comparator.comparing(Employee::getSalary))
    .limit(10)  // Lowest 10 salaries

Key Takeaway: sorted() before limit() forces full sorting of the entire stream, which is correct for "top N" queries but expensive—always consider whether you truly need sorting before limiting.