实现说明
TreeMap 有序范围查找可以归结为类 RateLadder和函数 main。
驱动整个流程的是 for (int quantity : new int[] {5, 250, 5000}) 这一个循环。
使用要点
- 每一步打印都带着自己的标签:
qty、headMap(100):、tailMap(100):。
常见问题
运行「TreeMap 有序范围查找」会打印什么?
运行文件本身,qty、headMap(100):、tailMap(100): 这些前缀各对应一段演示逻辑。
核心语句
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);
代码示例
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());
}
}