Example 1 — Shipping Price by Weight Band
Each key is the lowest weight of a band. floorEntry finds the band a parcel belongs to.
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
public class CollectionsUnmodifiableNavigableMapShip {
public static void main(String[] args) {
NavigableMap<Integer, Integer> table = new TreeMap<>();
table.put(0, 5);
table.put(2, 9);
table.put(10, 20);
NavigableMap<Integer, Integer> rates = Collections.unmodifiableNavigableMap(table);
int[] weights = {1, 2, 7, 25};
for (int kg : weights) {
System.out.println(kg + " kg -> $" + rates.floorEntry(kg).getValue());
}
}
} How It Works
- Bands as keys. 0, 2, and 10 kg start the three price bands of $5, $9, and $20.
- Round down to a band.
floorEntry(7)finds the greatest key not above 7, which is 2, so the price is $9. - Exact and large weights. 2 kg matches its key exactly, and 25 kg falls into the open-ended band starting at 10.

