Sort a stream and limit to take the largest or smallest N elements.
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);
[9, 7, 5]
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