Performance Considerations: sorted vs Pre-Sorted Collections
You'll learn when to sort in a stream pipeline versus choosing a pre-sorted collection upfront.
The Core Tradeoff
When you need sorted data, you have two main approaches:
- Use
sorted()in your stream pipeline on an unsorted collection - Start with a pre-sorted collection like
TreeSetor a manually sortedList
The right choice depends on how often you need sorted access and what operations you're performing.
When sorted() Makes Sense
Use sorted() in streams when:
- You only need sorted data once or occasionally
- You're already transforming data in a pipeline (filter, map, etc.)
- Your source collection changes frequently and maintaining sorted order is costly
List<String> names = new ArrayList<>();
// ... names populated dynamically ...
names.stream()
.filter(n -> n.startsWith("A"))
.sorted()
.forEach(System.out::println);
When Pre-Sorted Collections Win
Choose TreeSet or pre-sorted List when:
- You need repeated sorted access (multiple iterations, queries)
- Sorting cost can be amortized over many operations
- You need range queries or sorted iteration frequently
TreeSet<String> names = new TreeSet<>();
// Maintains sorted order automatically
names.add("Charlie");
names.add("Alice");
// Already sorted for any iteration
names.forEach(System.out::println);
The Performance Reality
sorted() creates temporary storage and sorts every time the pipeline executes. With TreeSet, you pay insertion cost once (O(log n) per insert) but get sorted iteration "free." For a single sort operation, the difference is negligible. For repeated access, pre-sorted collections dramatically outperform repeated sorted() calls.
Key Takeaway: Use sorted() for one-off transformations in pipelines; use TreeSet or pre-sorted collections when you need sorted access repeatedly or frequently.