java之TreeMap

发布时间 2023-04-25 16:36:33作者: Mars.wang

jdk中的TreeMap是一个宝藏类,里面包含了许多好用的方法

如果在内存中构建索引,我认为TreeMap更简单,性能更好,是比B+树更好的选择

public class Test {
    public static void main(String[] args) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        map.put(1,10);
        map.put(5,15);
        map.put(3,11);
        map.put(7,14);
        map.put(9,19);
        //比当前key小的最大entry,如果map中包含当前key,那就是key本身
        Map.Entry<Integer, Integer> entry = map.floorEntry(3);
        System.out.println(entry);
        //比当前key大的最小entry,如果当前key存在,那就是key本身
        Map.Entry<Integer, Integer> entry1 = map.ceilingEntry(5);
        System.out.println(entry1);
        //大于等于3,且小于7的子Map,也可以选择包含或不包含当前元素
        SortedMap<Integer, Integer> subMap = map.subMap(3, 7);
        System.out.println(subMap);
        //小于等于3的子map
        NavigableMap<Integer, Integer> head = map.headMap(3, true);
        System.out.println(head);
        //大于5的子map
        NavigableMap<Integer, Integer> tail = map.tailMap(5, false);
        System.out.println(tail);
        Integer firstKey = map.firstKey();
        Integer lastKey = map.lastKey();
        //floorKey(key), ceilingKey(key) 是包含key在内的上限下限 lowerKey(key), higherKey(key) 是不包含key的上限下限
        System.out.printf("first=%d,last=%d\n",firstKey,lastKey);
        Integer higherKey = map.higherKey(5);
        Integer lowerKey = map.lowerKey(3);
        System.out.printf("key=4,highKey=%d,lowKey=%d\n",higherKey,lowerKey);
        //逆序视图
        NavigableMap<Integer, Integer> descendingMap = map.descendingMap();
        System.out.println(descendingMap);
    }
}