Maps: floorKey and ceilingKey find the nearest key

These NavigableMap lookups answer "closest match" questions - the basis of range lookups like price bands or rate tables.

Code
NavigableMap<Integer, String> bands = new TreeMap<>();
bands.put(0, "free");
bands.put(100, "starter");
bands.put(500, "pro");

System.out.println("floorKey(250)   = " + bands.floorKey(250) + " -> " + bands.floorEntry(250).getValue());
System.out.println("ceilingKey(250) = " + bands.ceilingKey(250));
System.out.println("firstEntry      = " + bands.firstEntry());
System.out.println("lastEntry       = " + bands.lastEntry());
System.out.println("higherKey(500)  = " + bands.higherKey(500));
Output
floorKey(250)   = 100 -> starter
ceilingKey(250) = 500
firstEntry      = 0=free
lastEntry       = 500=pro
higherKey(500)  = null
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