TreeMap 常用函数

Java TreeMap

public class TestTreeMap {
    public static void main(String[] args) {
        TreeMap<Integer, String> pairs = new TreeMap<>();
        // 1,2,3,4
        pairs.put(1,"a");
        pairs.put(3,"b");
        pairs.put(6,"c");
        pairs.put(10,"d");
        System.out.println(pairs.ceilingKey(3));// 大于等于key中最近的
        System.out.println(pairs.ceilingKey(4));
        // 3 6
        System.out.println(pairs.floorKey(3)); // 小于等于中最近的
        System.out.println(pairs.floorKey(4));
        // 3 3
        System.out.println(pairs.higherKey(3)); //大于Key中最近的
        System.out.println(pairs.higherKey(4));
        // 6 6
        System.out.println(pairs.lowerKey(3)); // 小于key中最近的
        System.out.println(pairs.lowerKey(4));
        // 1 3

        System.out.println(pairs.firstKey()); //the first (lowest) key
        System.out.println(pairs.lastKey()); //  the last (highest) key
        // 1 10
    }
}

可以用于实现权值随机算法。

原文地址:https://www.cnblogs.com/lixyuan/p/13701644.html