Video in progress
You need to find the top 10 largest elements in a stream of several million. Why is sorted().limit(10) bad, and how do you write it?
sorted() is stateful: it gathers all the elements into memory and sorts them fully, O(n log n) time and O(n) memory, even though the result you need is only 10. A min-heap (PriorityQueue) of size k needs just O(n log k) time and O(k) memory. For parallel, each chunk has its own heap and a combiner.
📖 Answer
The JDK doesn't specially optimize the sorted().limit(k) combination: sorted first takes the whole stream into a buffer. 5 million objects means hundreds of megabytes and a full sort. If the source is Files.lines or a DB stream, the entire benefit of lazy reading is lost.
A collector with a heap:
static <T> Collector<T, ?, List<T>> topK(int k, Comparator<? super T> cmp) {
return Collector.of(
() -> new PriorityQueue<T>(k + 1, cmp), // min-heap: the smallest is on top
(heap, t) -> {
heap.offer(t);
if (heap.size() > k) heap.poll(); // we evict the smallest
},
(left, right) -> { // merging parallel chunks
right.forEach(t -> {
left.offer(t);
if (left.size() > k) left.poll();
});
return left;
},
heap -> heap.stream().sorted(cmp.reversed()).toList());
}
List<Order> biggest = orders.stream().collect(topK(10, Comparator.comparing(Order::amount)));
Why a min-heap: we keep the largest ones, so the "candidate to evict" is the smallest among those kept, and it needs to be on top.
Things to watch for:
- Ties: if there are orders with equal amounts at position 10, which one gets in depends on the heap order. If you need a deterministic result, add a second criterion to the comparator (
thenComparing(Order::id)). - Parallel: the collector isn't
UNORDERED, but the result doesn't depend on order, so if you like you can addCollector.Characteristics.UNORDERED. Test the combiner separately withparallel(). - If k is large (say, half a million), the heap loses its advantage, and a plain sort is simpler.
And most important: if the data is in a database, don't bring this into Java. ORDER BY amount DESC LIMIT 10 with a suitable index takes a few milliseconds. Top-K in Java is for logs, files, an in-memory cache or data gathered from several sources.
Sign up to mark studied questions and save your progress.