TreeMap API
简介
TreeMap,简单理解就是有序的Map。底层原理是红黑树。
这篇文章主要总结了一下API的用法,不涉及原理分析。
几个函数式接口介绍
1.BiConsumer
@FunctionalInterface
public interface BiConsumer<T, U> {
/**
* 在forEach中使用了该接口
*
* @param t the first input argument
* @param u the second input argument
*/
void accept(T t, U u);
}
2.Function
@FunctionalInterface
public interface Function<T, R> {
/**
* 将T执行某种操作转为R,在computeIfAbsent等方法使用了该接口
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
3.BiFunction
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* 将T和U执行某种操作,返回结果R,在computeIfPresent/merge等方法使用了该接口
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
}
说明:上述接口是出于通用的目的定义的,从方法名可以看出。Function就是功能的意思,具体的含义由程序员的具体实现来决定。
TreeMap类图
类图中只列出了TreeMap相关的方法;以及Map接口中,自Java1.8以来新增的方法。
SortedMap接口
从名字可以看出,该接口定义了“有序的Map”类型。、
SortedMap,以及接下来学习的TreeMap,都是根据key值进行排序。key的排序规则默认按自然序,并且可以提供Comparator接口以提供排序的”策略“。
SortedMap中主要提供了获取子map的方法。同时提供了firstKey和lastKey两个方法获取有序列表中第一个key和最后一个key。
public class Test {
public static void main(String[] args) {
SortedMap<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>();
for (int i = 0; i < 10; i++) {
sortedMap.put(i, i * i);
}
SortedMap<Integer, Integer> headMap = sortedMap.headMap(5); //取<=5的key之前的子map
System.out.println("headMap : " + headMap);
SortedMap<Integer, Integer> tailMap = sortedMap.tailMap(5); //取>=5的key之后的子map
System.out.println("tailMap : " + tailMap);
headMap.clear();
tailMap.clear();
System.out.println("sortedMap.size : " + sortedMap.size()); //将会是0
}
}
NavigableMap接口
SortedMap提供了获取有序子map的接口,但还是不够方便。
jdk提供了NavigableMap接口,使我们可以方便地遍历和操作Map。
获取相应key的方法:
K lowerKey(K key) // gotKey < key
K floorKey(K key) // gotKey <= key
K higherKey(K key) // gotKey > key
K ceilingKey(K key) // gotKey >= key
获取/操作相应Entry的方法:
Map.Entry<K,V> lowerEntry(K key) // entry.key < key
Map.Entry<K,V> higherEntry(K key) // entry.key > key
Map.Entry<K,V> floorEntry(K key) // entry.key <= key
Map.Entry<K,V> ceilingEntry(K key) // entry.key >= key
Map.Entry<K,V> firstEntry(K key) //获取第一个Entry
Map.Entry<K,V> lastEntry(K key) //获取最后一个Entry
//-------------类似队列/栈的操作---------------
Map.Entry<K,V> pollFirstEntry() //获取并删除第一个Entry
Map.Entry<K,V> pollLastEntry() //获取并删除最后一个Entry
其他的方法都是针对Map有序而定制的,具体使用查看Javadoc即可。