TreeMap
- TreeMap 使用树实现 Map 接口,可以按顺序存储键-值对,底层的数据结构是红黑树;
- TreeMap 实现了SortedMap 并且扩展(即继承)了 AbstractMap,可以对键对象排序,本身没有定义其他的方法,排序方式有两种:自然排序和比较器排序;
- java.util.TreeMap<K,V>,详见:Class TreeMap<K,V>;
1. 构造方法
构造方法 | 说明 |
---|
TreeMap() | 空的 TreeMap,根据键自然排序 |
TreeMap(Comparator c) | 空的 TreeMap,根据给定比较器排序 |
TreeMap(Map m) | 包含相同映射的新映射,根据键自然排序 |
TreeMap(Comparator<? super K> comparator) | 包含相同映射的新映射,顺序与原映射一致 |
2. 类的使用
a. 转变为集合的遍历
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;
public class test {
public static void main(String[] args) {
TreeMap tm = new TreeMap();
tm.put((100 - 20), "good");
tm.put((100 - 30), "bad");
tm.put((100 - 10), "excellent");
Collection c = tm.values();
Iterator it = c.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
b. 自然排序
import java.util.TreeMap;
public class test {
public static void main(String[] args) {
TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
tm.put(1, "张三");
tm.put(4, "赵六");
tm.put(3, "王五");
tm.put(6, "酒八");
tm.put(5, "老七");
tm.put(2, "李四");
System.out.println(tm);
}
}
c. 比较器排序
import java.util.Comparator;
import java.util.Objects;
import java.util.TreeMap;
class Student {
private int age;
private String name;
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public Student() {}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
}
public class test {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<Student, String>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int result = o1.getAge() - o2.getAge();
if (result == 0) {
return o1.getName().charAt(0) - o2.getName().charAt(0);
} else {
return result;
}
}
});
tm.put(new Student(30, "jack"), "深圳");
tm.put(new Student(10, "rose"), "北京");
tm.put(new Student(20, "tom"), "上海");
tm.put(new Student(10, "marry"), "南京");
tm.put(new Student(30, "lucy"), "广州");
System.out.println(tm);
}
}