Collections: NavigableSet floor, ceiling and subSet

These methods answer nearest-neighbour questions without scanning, which is the reason to reach for a TreeSet over a HashSet.

Code
NavigableSet<Integer> marks = new TreeSet<>(List.of(35, 50, 65, 80, 95));

System.out.println("floor(70)   = " + marks.floor(70));
System.out.println("ceiling(70) = " + marks.ceiling(70));
System.out.println("higher(80)  = " + marks.higher(80));
System.out.println("headSet(65) = " + marks.headSet(65));
System.out.println("subSet(50, true, 80, true) = " + marks.subSet(50, true, 80, true));
Output
floor(70)   = 65
ceiling(70) = 80
higher(80)  = 95
headSet(65) = [35, 50]
subSet(50, true, 80, true) = [50, 65, 80]
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-30