sorted

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • sorted() is a stateful intermediate operation used to sort the elements in a stream.
  • sorted() uses the natural ordering (requires elements to implement Comparable).
  • sorted(Comparator<T>) uses a custom Comparator to dictate the sorting logic.

Concept

Sorting is inherently a stateful operation. The stream pipeline cannot emit the “first” element to the next stage until it has seen every single element in the stream to determine which one actually is the first.

Because of this, sorted() acts as a barrier in the pipeline. All previous operations must finish processing all elements before sorted() can do its job and release elements to the rest of the pipeline.

Examples

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortedExample {
    public static void main(String[] args) {
        
        List<String> names = Arrays.asList("Zack", "Alice", "Bob", "Charlie");
        
        // 1. Natural Ordering (Alphabetical)
        List<String> natural = names.stream()
            .sorted()
            .collect(Collectors.toList());
        System.out.println(natural); // [Alice, Bob, Charlie, Zack]
        
        // 2. Reverse Order (Using Comparator)
        List<String> reverse = names.stream()
            .sorted(Comparator.reverseOrder())
            .collect(Collectors.toList());
        System.out.println(reverse); // [Zack, Charlie, Bob, Alice]
        
        // 3. Custom Comparator (Sort by length)
        List<String> lengthSort = names.stream()
            .sorted(Comparator.comparingInt(String::length))
            .collect(Collectors.toList());
        System.out.println(lengthSort); // [Bob, Zack, Alice, Charlie]
    }
}

Interview Questions

Q: What happens if you call sorted() on a stream of objects that do not implement Comparable?
A: If you call the no-argument .sorted() on objects that do not implement Comparable, the code will compile fine, but it will throw a ClassCastException at runtime when it attempts to sort them. To fix this, you must either make the class implement Comparable or provide a custom Comparator to .sorted().

Q: Why should you put filter() before sorted() in a stream pipeline?
A: Performance. Sorting is an expensive O(Nlog⁡N)O(N \log N) operation. If you sort a list of 10,000 items, and then filter out 9,000 of them, you wasted a massive amount of CPU cycles sorting items that you eventually threw away. If you filter first, you only sort the 1,000 items you actually care about.