本文主要学习TreeMap的核心API,下面是测试数据:
TreeMap< Long, Long> treeMap = new TreeMap<>();
for(int i = 2; i <= 20; i = i + 2) {
treeMap.put(new Long(i), new Long(i));
}
1、K lowerKey(K key) | Map.Entry< K,V> lowerEntry(K key)
1)英文注释
Returns a key-value mapping associated with the greatest keystrictly less than the given key, or {@code null} if there is no such key.
2)测试结果
输出结果:
4
4
null
3)中文解释
返回第一个小于该key的键或Entry,不包含指定key。指定key不存在不影响结果,例如测试用例中的不存在键为5的键值对,但还是能返回Key:4,如果没有扎到小于key的键,则返回null。
2、K floorKey(K key) | Map.Entry< K,V> floorEntry(K key)
1)英文注释
Returns a key-value mapping associated with the greatest key less than or equal to the given key, or {@code null} if there is no such key。
2)测试结果
输出结果:
6
4
null
3)中文解释
返回小于等于指定key的键值,与lowerKey的区别是floorKey方法,如果TreeMap中包含指定的key,则返回指定key,否则返回第一个小于指定key的键。
3、K ceilingKey(K key) | Map.Entry< K,V> ceilingEntry(K key)
1)英文注释
Returns a key-value mapping associated with the least key greater than or equal to the given key, or {@code null} if there is no such key。
2)测试结果
输出结果:
6
6
null
3)中文解释
ceiling : 天花板,查找指定key的天花板,也就是说,查找第一个大于等于指定key的可以。
4、K higherKey(K key) | Map.Entry< K,V> higherEntry(K key)
1)英文注释
Returns a key-value mapping associated with the least key strictly greater than the given key, or {@code null} if there is no such key。
2)测试结果
输出结果:
8
6
null
3)中文解释
返回第一个大于指定key的键,不包含指定key。而ceilingKey包含指定key。
5、Map.Entry< K,V> firstEntry()、Map.Entry< K,V> lastEntry()、Map.Entry< K,V> pollFirstEntry()、Map.Entry< K,V> pollLastEntry()
这四个方法很好理解,这里不做详细讲解。
6、NavigableMap< K,V> descendingMap()、 NavigableSet< K> descendingKeySet()
这两个方法,返回逆序。
7、NavigableMap< K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
1)英文注释
2)测试结果
输出结果:
{4=4, 6=6, 8=8}
返回子集合(TreeMap),从fromKey,到toKey,boolean fromInclusive表示是否包含fromKey,boolean toInclusive是否包含toKey。
TreeMap#subMap
public SortedMap<K,V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
8、NavigableMap< K,V> headMap(K toKey, boolean inclusive)
1)英文注释
2)中文说明
测试结果省略(推理后,也验证过),根据上面的学习过程,可以推导出,该方法相当于 subMap(firstKey, true, toKey, inclusive)。
TreeMap#headMap(Key toKey)
public SortedMap<K,V> headMap(K toKey) {
return headMap(toKey, false);
}
9、NavigableMap< K,V> tailMap(K fromKey, boolean inclusive)
1)英文描述
2)中文解释
返回从fromKey到lastKey的子集合,相当于subMap(fromKey,inclusive,lastKey,true)。
TreeMap#tailMap(K fromKey)
public SortedMap<K,V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
欢迎加笔者微信号(dingwpmz),加群探讨,笔者优质专栏目录:
1、源码分析RocketMQ专栏(40篇+)
2、源码分析Sentinel专栏(12篇+)
3、源码分析Dubbo专栏(28篇+)
4、源码分析Mybatis专栏
5、源码分析Netty专栏(18篇+)
6、源码分析JUC专栏
7、源码分析Elasticjob专栏
8、Elasticsearch专栏(20篇+)
9、源码分析MyCat专栏