TreeMap Navigable Range Lookups

Answer threshold pricing with floorEntry plus ceilingKey, floorKey, and the headMap and tailMap range views on a key-sorted TreeMap.

JavaData Fetching

Code

snippet
import java.util.NavigableMap;
import java.util.TreeMap;

public class RateLadder {

    public static void main(String[] args) {
        // 阶梯价:购买量达到门槛即适用对应单价
        NavigableMap<Integer, Double> ladder = new TreeMap<>();
        ladder.put(0, 1.00);
        ladder.put(100, 0.80);
        ladder.put(1000, 0.60);

        for (int quantity : new int[] {5, 250, 5000}) {
            var tier = ladder.floorEntry(quantity); // lookup:不高于该量的最大门槛
            System.out.printf("qty %d -> threshold %d, unit %.2f%n",
                    quantity, tier.getKey(), tier.getValue());
        }

        // range 视图:headMap/tailMap 按 key 范围切分
        System.out.println("headMap(100): " + ladder.headMap(100));
        System.out.println("tailMap(100): " + ladder.tailMap(100));

        System.out.println("ceiling 150: " + ladder.ceilingKey(150));
        System.out.println("floor 150: " + ladder.floorKey(150));
        System.out.println("first: " + ladder.firstEntry() + ", last: " + ladder.lastEntry());
    }
}

Inside the snippet

TreeMap Navigable Range Lookups comes down to the class RateLadder and the function main.

Repetition is confined to for (int quantity : new int[] {5, 250, 5000}) — the rest of the file is straight-line. The try-with-resources form guarantees each declared resource is closed even when the body throws.

Putting it to use

The demo output is labeled (qty, headMap(100):, tailMap(100):), so every printed line maps back to its originating operation.

Core lines

var tier = ladder.floorEntry(quantity); // lookup:不高于该量的最大门槛
System.out.printf("qty %d -> threshold %d, unit %.2f%n",
quantity, tier.getKey(), tier.getValue());
NavigableMap<Integer, Double> ladder = new TreeMap<>();
ladder.put(1000, 0.60);

Interactive Tools for This Topic

FAQ

What does TreeMap Navigable Range Lookups print when run?
Execute the whole file; each printed line is prefixed with a label like `qty`, `headMap(100):`, `tailMap(100):`.