Java TreeMap ceilingKey() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

In Java, ceilingKey(key) returns the least key greater than or equal to key in a TreeMap, or null if no key is that large. A key that is present returns itself.

Use it for "the next one from here": the next departure, the smallest container that fits, or the first word that starts with a prefix. It belongs to NavigableMap (Java 6) and takes O(log n) time.

An instance method of java.util.TreeMap, added in Java 6 (JDK 1.6) with the NavigableMap interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

Give a probe value; the map rounds it up to a key.

Java
TreeMap<String, Integer> buses = new TreeMap<>();
buses.put("07:35", 12);
buses.put("08:05", 31);
String next = buses.ceilingKey("07:40");   // "08:05"
String none = buses.ceilingKey("09:00");   // null
CallWhat it does
map.ceilingKey(k)Least key ≥ k, or null.
map.higherKey(k)Least key strictly above k.
map.ceilingEntry(k)The same key paired with its value.

Keep the result in a reference type such as Integer or String and test it for null; probes above the largest key have no ceiling.

Library declarations
Java
// java.util.TreeMap<K, V>
public K ceilingKey(K key)

// Declared in NavigableMap<K, V> (Java 6)

Parameters

ParameterDescription
key (K)The value to round up from; it may or may not be a key.

Return Value

Return ValueDescription
KThe least key that compares greater than or equal to key.
nullAll keys are smaller than key, or the map is empty.

Compare with Similar Methods

Related lookups around a probe value:

MethodHow it differs
higherKey(k)Never returns k itself.
floorKey(k)Rounds down instead of up.
ceilingEntry(k)Gives the value as well as the key.
tailMap(k)Every key from k upward, as a live view.

Java Examples

Example 1 — Catch the Next Bus

Arrival times are probes; ceilingKey picks the first departure at or after each one.

Java
import java.util.TreeMap;

public class TreeMapCeilingKeyBus {
    public static void main(String[] args) {
        TreeMap<String, Integer> buses = new TreeMap<>();
        buses.put("07:05", 12);
        buses.put("07:35", 12);
        buses.put("08:05", 31);
        buses.put("08:50", 12);

        String[] arrivals = {"07:35", "07:40", "09:00"};
        for (String t : arrivals) {
            String next = buses.ceilingKey(t);
            if (next == null) {
                System.out.println("at " + t + ": no more buses today");
            } else {
                System.out.println("at " + t + ": catch the " + next + " (route " + buses.get(next) + ")");
            }
        }
    }
}

How It Works

  1. Arriving right on time. "07:35" is a key, and the "or equal" part of ceilingKey lets the passenger board that very bus.
  2. Five minutes late. 07:40 sits between two departures, so the method rounds up to "08:05", route 31.
  3. After the last bus. Every key is earlier than "09:00", the result is null, and the program prints the "no more buses" branch.

Example 2 — Choose the Smallest Box That Holds an Order

Keys are box capacities in litres; the ceiling of the needed volume is the tightest fit.

Java
import java.util.TreeMap;

public class TreeMapCeilingKeyBoxSize {
    public static void main(String[] args) {
        TreeMap<Integer, String> boxes = new TreeMap<>();
        boxes.put(5, "small box");
        boxes.put(20, "medium box");
        boxes.put(60, "large box");

        int[] needs = {3, 20, 75};
        for (int litres : needs) {
            Integer size = boxes.ceilingKey(litres);
            String choice = (size == null) ? "split the order" : boxes.get(size);
            System.out.println(litres + " L -> " + choice);
        }
    }
}

How It Works

  1. Smallest capacity that is big enough. 3 litres rounds up to the 5-litre key, so no larger box is wasted on a tiny order.
  2. A perfect fit. 20 litres matches the medium box exactly, and an exact key is its own ceiling.
  3. Too big for any box. 75 is above the largest capacity, so size is null and the conditional switches to "split the order".

Example 3 — Autocomplete Words From a Prefix

All words that start with a prefix form one block in sorted order, and ceilingKey(prefix) is the start of that block.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class TreeMapCeilingKeyPrefix {
    static void suggest(TreeMap<String, Integer> words, String prefix) {
        List<String> found = new ArrayList<>();
        String k = words.ceilingKey(prefix);
        while (k != null && k.startsWith(prefix)) {
            found.add(k);
            k = words.higherKey(k);
        }
        System.out.println(prefix + " -> " + (found.isEmpty() ? "no suggestions" : found));
    }

    public static void main(String[] args) {
        TreeMap<String, Integer> words = new TreeMap<>();
        String[] list = {"cat", "care", "car", "dog", "cart", "card"};
        for (String w : list) {
            words.put(w, w.length());
        }
        suggest(words, "car");
        suggest(words, "do");
        suggest(words, "cas");
    }
}

How It Works

  1. Start of the block. "car" is a key, so ceilingKey("car") returns it; the loop then steps forward with higherKey through card, care, and cart.
  2. Stop at the first non-match. After "cart" comes "cat", which does not start with "car", so the loop ends without scanning the rest of the map.
  3. Rounded up past the prefix. For "cas" the ceiling is "cat", which fails startsWith, so the list stays empty and "no suggestions" is printed.

Frequently Asked Questions

The least key greater than or equal to the argument, or null if every key is smaller.
ceilingKey() returns the argument itself when it is a key; higherKey() always returns a strictly greater key.
No key in the map is greater than or equal to the argument, or the map is empty. It is a normal result, not an error.
Yes. With String keys, ceilingKey(prefix) is the first key that could start with the prefix; loop with higherKey() while startsWith(prefix) is true.
Not with natural ordering on a non-empty map: it throws NullPointerException because null cannot be compared.

Next: clear()

Remove every mapping and leave an empty map.

clear() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful