sorted().limit(k) has to materialise and sort everything. A min-heap of size k keeps only k rows in memory no matter how long the feed is - which is the difference between a report and an OutOfMemoryError.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-20