首先举例基本的用法:TreeMap默认是按照key进行排序,要是遇到key相同的话,只输出一个数值。
1.基础用法
package testpro;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class Demo2 {
public static void main(String[] args) {
TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
tm.put("a", 1);
tm.put("ab", 15);
tm.put("ba", 51);
tm.put("bc", 19);
tm.put("a", 17);
tm.put("da", 0);
Set<Entry<String, Integer>> set1 = tm.entrySet();
for(Entry<String, Integer> s: set1) {
System.out.println(s.getKey() + ":" + s.getValue());
}
}
}
结果如下:
a:17
ab:15
ba:51
bc:19
da:0
2.升级版
我这里根据TreeMap的性质对其进行功能拓展:
我想对学生按照年龄进行从大到小排序,要是年龄相同,就根据名字排序,所以将学生的信息封装在Student的类中,然后将这个类放在TreeMap的key的位置,再传入一个比较器,就可以进行比较
这是Student类:
package testpro;
public class Student{
private String name;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
这是比较类:
package testpro;
import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
public class Demo2 {
//TreeMap默认是按照key进行排序,要是遇到key相同的话,只输出一个数值。
public static void main(String[] args) {
TreeMap<Student, Integer> tm = new TreeMap<Student, Integer>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge() == o2.getAge()) {
return o1.getName().compareTo(o2.getName());
}
return o2.getAge() - o1.getAge();
}
});
Student s1 = new Student("a",2);
Student s2 = new Student("ab",23);
Student s3 = new Student("a",28);
Student s4 = new Student("ba",29);
Student s5 = new Student("ca",2);
tm.put(s1,1);
tm.put(s2,1);
tm.put(s3,1);
tm.put(s4,1);
tm.put(s5,1);
Set<Entry<Student, Integer>> set1 = tm.entrySet();
for(Entry<Student, Integer> s: set1) {
System.out.println(s.getKey());
}
}
}
结果如下:
Student [name=ba, age=29]
Student [name=a, age=28]
Student [name=ab, age=23]
Student [name=a, age=2]
Student [name=ca, age=2]