- 新建时候可以指定排序依据 new TreeMap<>(new Comparator() {})
- ceilingEntry(TreeMap下的方法),获取就近key的值的键值对(可以取等),向上取整,倒序之后会相反。返回Entry类型
- lowerEntry方法 返回严格小于给定键的键值对(不可取等)
- ceilingKey(TreeMap下的方法),获取就近key的值(可以取等),向上取整,倒序之后会相反。返回map中key的类型
- lowerKey(key) 返回小于key的最近的键值(不可取等)
- firstEntry/lastEntry返回最小/最大键的键值对
- tailMap 返回给定键之后的键值对,传入第二个参数可以选择包括传入key,默认为true
- subMap 返回切割map 可以传入inclusive表示是否包涵
import java.util.Comparator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapUse {
public static void main(String[] args) {
// 传入比较器说明排序方式
TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// 升序
return Integer.compare(o1, o2);
}
});
map.put(2, "aaa");
map.put(18, "aaa");
map.put(4, "aaa");
map.put(15, "aaa");
map.put(7, "aaa");
System.out.println(map);
// ceilingEntry(TreeMap下的方法),获取就近key的值的键值对(可以取等),向上取整,倒序之后会相反。返回Entry类型
Map.Entry<Integer, String> ceil = map.ceilingEntry(5);
System.out.println(ceil);
// lowerEntry方法 返回严格小于给定键的键值对(不可取等)
Map.Entry<Integer, String> lower = map.lowerEntry(7);
System.out.println(lower);
// ceilingKey(TreeMap下的方法),获取就近key的值(可以取等),向上取整,倒序之后会相反。返回map中key的类型
Integer ceilKey = map.ceilingKey(9);
System.out.println(ceilKey);
//向下取,不可取等
Integer lowKey = map.lowerKey(9);
system.out.println(lowKey);
// 返回最小/最大键的键值对
Map.Entry<Integer, String> min = map.firstEntry(); // 最小,相应还有firstKey()
Map.Entry<Integer, String> max = map.lastEntry(); // 最大 相应还有lastKey()
System.out.println("min---- " + min + " max---- " + max);
// tailMap 返回给定键之后的键值对,传入第二个参数可以选择包括传入key,默认为true
SortedMap<Integer, String> tailMap = map.tailMap(7);
System.out.println(tailMap);
// subMap 返回切割map 可以传入inclusive表示是否包涵
SortedMap<Integer, String> subMap = map.subMap(7, true, 18,true);
System.out.println(subMap);
}
}
————————————————
版权声明:本文为CSDN博主「noobmantest」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43960044/article/details/116459372