Java TreeMap floorKey() Method

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

Definition

In Java, floorKey(key) returns the greatest key less than or equal to key in a TreeMap, or null when every key is larger. An exact match counts, so a key that is present returns itself.

It answers "which band does this value fall into?": tax brackets, price tiers, or the last known rate before a date. The method was added in Java 6 with NavigableMap and runs in 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

Pass any probe value, present in the map or not.

Java
TreeMap<Integer, Integer> rates = new TreeMap<>();
rates.put(0, 0);
rates.put(12000, 10);
Integer band = rates.floorKey(30000);   // 12000
Integer none = rates.floorKey(-5);      // null
CallWhat it does
map.floorKey(k)Greatest key ≤ k, or null.
map.floorEntry(k)The same position, with its value.
map.lowerKey(k)Greatest key strictly below k.

Assigning the result straight to a primitive (int band = map.floorKey(x);) is only safe when a key exists at or below every probe, for example a band that starts at 0. Otherwise keep it as Integer and test for null.

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

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

Parameters

ParameterDescription
key (K)The value to search from. It does not have to be in the map.

Return Value

Return ValueDescription
KThe greatest key that compares less than or equal to key.
nullEvery key in the map is greater than key, or the map is empty.

Compare with Similar Methods

The four "nearest key" methods side by side:

MethodHow it differs
lowerKey(k)Like floorKey but skips an exact match.
ceilingKey(k)Smallest key greater than or equal to k.
floorEntry(k)Returns the key and value together.
headMap(k, true)All keys at or below k, not just the nearest.

Java Examples

Example 1 — Pick the Tax Band for an Income

Each key is the lower edge of a band; floorKey finds the band an income falls into.

Java
import java.util.TreeMap;

public class TreeMapFloorKeyTax {
    public static void main(String[] args) {
        TreeMap<Integer, Integer> rates = new TreeMap<>();
        rates.put(0, 0);
        rates.put(12000, 10);
        rates.put(40000, 20);
        rates.put(100000, 40);

        int[] incomes = {8000, 40000, 65500, 250000};
        for (int income : incomes) {
            int band = rates.floorKey(income);
            System.out.println(income + " -> band from " + band + ", rate " + rates.get(band) + "%");
        }
    }
}

How It Works

  1. Bands as lower edges. Storing only where each band starts is enough: 8000 has 0 as its nearest key at or below, so the rate is 0%.
  2. A boundary belongs to its own band. 40000 is itself a key, and because floorKey includes equality the income lands in the 20% band rather than the 10% one.
  3. No upper limit needed. 250000 is above every key, and the floor is simply the top band starting at 100000; the key 0 also guarantees a non-null result for the int.

Example 2 — Spend Thresholds and the null Below the First One

A shop gives rewards from 50 and 100 upward; totals under 50 have no floor key.

Java
import java.util.TreeMap;

public class TreeMapFloorKeyBelowMin {
    public static void main(String[] args) {
        TreeMap<Integer, String> rewards = new TreeMap<>();
        rewards.put(50, "free bag");
        rewards.put(100, "free delivery");

        int[] totals = {30, 50, 99};
        for (int total : totals) {
            Integer tier = rewards.floorKey(total);
            if (tier == null) {
                System.out.println(total + ": no reward yet, spend " + (rewards.firstKey() - total) + " more");
            } else {
                System.out.println(total + ": " + rewards.get(tier));
            }
        }
        try {
            rewards.floorKey(null);
        } catch (NullPointerException e) {
            System.out.println("floorKey(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Below the lowest threshold. No key is at or under 30, so floorKey returns null; the code then uses firstKey() to say how far away the first reward is.
  2. Close to the next tier still counts as the lower one. 99 is just short of 100, and its floor is 50, so the customer gets the bag but not free delivery.
  3. null is not a valid probe. The tree must compare the probe with its keys, and natural ordering cannot compare null, hence the exception.

Example 3 — Use the Most Recent Exchange Rate for Any Day

Rates exist only on trading days; a weekend date falls back to the latest earlier date.

Java
import java.util.TreeMap;

public class TreeMapFloorKeyDates {
    public static void main(String[] args) {
        TreeMap<String, Double> eurUsd = new TreeMap<>();
        eurUsd.put("2026-03-04", 1.08);
        eurUsd.put("2026-03-05", 1.09);
        eurUsd.put("2026-03-06", 1.07);
        eurUsd.put("2026-03-09", 1.1);

        String[] days = {"2026-03-05", "2026-03-08", "2026-03-01"};
        for (String day : days) {
            String known = eurUsd.floorKey(day);
            System.out.println(day + " uses rate of " + known + (known == null ? "" : " = " + eurUsd.get(known)));
        }
    }
}

How It Works

  1. ISO dates sort correctly as text. The year-month-day format with zero padding means string order and calendar order agree, so a String key works here.
  2. Sunday borrows Friday's rate. 2026-03-08 has no entry, and the greatest date at or before it is 2026-03-06, giving 1.07.
  3. Before the data starts. 2026-03-01 precedes the first stored day, so known is null and the conditional skips the rate.

Frequently Asked Questions

The greatest key less than or equal to the given key. If the key itself is present, it is returned; if every key is larger, the result is null.
floorKey() accepts an exact match; lowerKey() is strictly less, so for a key that is present lowerKey() returns the previous key.
No. Any value of the key type works, which is what makes it useful for bands and ranges.
Yes. A null argument throws NullPointerException under natural ordering, and an incomparable type throws ClassCastException.
In Java 6, as part of the NavigableMap interface that TreeMap implements.

Next: forEach()

Run a lambda for every key and value in sorted order.

forEach() 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.

14 people found this page helpful