TreeMap
TreeMap一般用来快速查找数据,他的键值是不重复的,默认按照从小到大排序,键值排序通常有两种方式实现Comparable或者实现比较器Comparator.
1.创建对象
TreeMap map = new TreeMap()
TreeMap map = new TreeMap(比较器)
2.简单测试
public class Test1 {
public static void main(String[] args) {
TreeMap<Integer,String> map = new TreeMap<>();
map.put(3333, "3");
map.put(1111, "1");
map.put(2222, "2");
map.put(7777, "7");
map.put(4444, "4");
map.put(6666, "6");
map.put(5555, "5");
System.out.println(map);//{1111=1, 2222=2, 3333=3, 4444=4, 5555=5, 6666=6, 7777=7}
System.out.println(map.size());//7
System.out.println(map.get(7777));//7
System.out.println(map.remove(4444));//4
System.out.println(map);//{1111=1, 2222=2, 3333=3, 5555=5, 6666=6, 7777=7}
}
}
3.关于比较器的小例子
public class Test { public static void main(String[] args) { Point a = new Point(1,18); Point b = new Point(2,25); Comparator<Point> comp = new Comparator<Point>() { @Override public int compare(Point lhs, Point rhs) { return rhs.getY()-lhs.getY(); } }; TreeMap<Point, String> map = new TreeMap<>(comp); map.put(a, "1.8亿"); map.put(b, "2.5亿"); System.out.println(map);//{(2,25)=2.5亿, (1,18)=1.8亿} } }
public class Point { private int x; private int y; public Point() { super(); } public Point(int x, int y) { super(); this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public String toString() { return "("+x+","+y+")"; } }