Java: Top-N elements with sorted + limit

Sort a stream and limit to take the largest or smallest N elements.

Code
List<Integer> nums = List.of(5, 1, 9, 3, 7, 2);
List<Integer> top3 = nums.stream()
        .sorted(Comparator.reverseOrder())
        .limit(3)
        .toList();
System.out.println(top3);
Output
[9, 7, 5]
Advertisement

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-07-26