TreeMap用法
“`
public class TreeMapT {
public static void main(String[] args) {
//treeMap默认升序 K不重复 匿名内部类重写compare方法改变排序方式(降序)
TreeMap<String,Integer> m = new TreeMap(new Comparator<String>() {
//根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
m.put("33", 33);
m.put("11", 11);
m.put("22", 22);
m.put("55", 55);
m.put("11", 33);
System.out.println(m);
System.out.println("===================jdk的方法=======================");
TreeMap<String,Integer> map = new TreeMap();
map.put("33", 33);
map.put("11", 11);
map.put("22", 22);
map.put("55", 55);
map.put("11", 33);
//Tree默认是升序
System.out.println("输出集合"+map);
//ceilingKey(K key) 返回大于等于给定键的最小键;如果不存在这样的键,则返回 null。
System.out.println("ceilingKey()"+map.ceilingKey("10"));
//ceilingEntry(K key) 返回一个键-值映射关系,它与大于等于给定键的最小键关联;如果不存在这样的键,则返回 null。
System.out.println("ceilingEntry(K key)"+map.ceilingEntry("44"));
//comparator() 返回对此映射中的键进行排序的比较器;如果此映射使用键的自然顺序,则返回 null
System.out.println("comparator() "+map.comparator());
// containsKey(Object key)如果此映射包含指定键的映射关系,则返回 true。
System.out.println("containsKey(Object key)"+map.containsKey("55"));
//containsValue(Object value) 如果此映射为指定值映射一个或多个键,则返回 true。
System.out.println("containsValue(Object value)"+map.containsValue(33));
//descendingKeySet() 返回此映射中所包含键的逆序 NavigableSet 视图。
NavigableSet<String> navigableKeySet = map.navigableKeySet();
System.out.println("descendingKeySet() "+navigableKeySet);
//descendingMap() 返回此映射中所包含映射关系的逆序视图。
System.out.println("descendingMap"+map.descendingMap());
//firstEntry() 返回一个与此映射中的最小键关联的键-值映射关系;如果映射为空,则返回 null。
System.out.println("firstEntry"+map.firstEntry());
//firstKey() 返回此映射中当前第一个(最低)键。
System.out.println("firstKey"+map.firstKey());
//floorEntry(K key) 返回一个键-值映射关系,它与小于等于给定键的最大键关联;如果不存在这样的键,则返回 null。
System.out.println("floorEntry"+map.floorEntry("44"));
//floorKey(K key) 返回小于等于给定键的最大键;如果不存在这样的键,则返回 null。
System.out.println("floorKey"+map.floorKey("44"));
//headMap(K toKey) 返回此映射的部分视图,其键值严格小于 toKey。
System.out.println("headMap"+map.headMap("44"));
//higherEntry(K key) 返回一个键-值映射关系,它与严格大于给定键的最小键关联;如果不存在这样的键,则返回 null。
System.out.println("higherEntry"+map.headMap("00"));
//higherKey(K key) 返回严格大于给定键的最小键;如果不存在这样的键,则返回 null。
System.out.println("hightKey"+map.higherKey("44"));
System.out.println("keySet() 返回此映射包含的键的 Set 视图");
Set<String> keySet = map.keySet();
for(String s : keySet){
System.out.println(s);
}
//subMap(K fromKey, K toKey)返回此映射的部分视图,其键值的范围从 fromKey(包括)到 toKey(不包括)。
System.out.println("subMap"+map.subMap("11", "33"));
//tailMap(K fromKey) 返回此映射的部分视图,其键大于等于 fromKey。
System.out.println("tailMap"+map.tailMap("33"));
}
}
“`