作者:李永健
撰写时间:2019年 07月25日
开发工具与关键技术:MyEclipse10,java
TreeMap中也提供了一系列根据key顺序访问key-value对的方法:
常用方法:
例子:
import java.util.TreeMap;
public class TreeManDemo {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "Str1");
map.put(2, "Str2");
map.put(3, "Str3");
map.put(4, "Str4");
map.put(5, "Str5");
System.out.println("打印集合 = "+map);
// 最低键
System.out.println("最低键 = "+map.firstKey());
//最小键值对
System.out.println("最小键值对 = "+map.firstEntry());
//最大键
System.out.println("最大键 = "+map.lastKey());
//最大键值对
System.out.println("最大键值对 = "+map.lastEntry());
//大于给定键的最小键
System.out.println("大于给定键的最小键 = "+map.higherKey(2));
//大于给定键的最小键关联
System.out.println("大于给定键的最小键关联 = "+map.higherEntry(2));
//小于给定键的最大键
System.out.println("小于给定键的最大键 = "+map.lowerKey(2));
//小于给定键的最大键关联
System.out.println("小于给定键的最大键关联 = "+map.lowerEntry(2));
//小于给定键的键值对(toKey)
System.out.println("小于给定键的键值对(toKey) = "+map.headMap(4));
//大于等于给定键的键值对(fromKey)
System.out.println("大于等于给定键的键值对(fromKey) = "+map.tailMap(4));
//fromKey(包括)到 toKey(不包括)
System.out.println("fromKey(包括)到 toKey(不包括) = "+map.subMap(2,5));
}
}
结果图: