版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/83088969
import java.util.Comparator;
import java.util.TreeMap;
import com.heima.bean.Student;
public class Demo7_TreeMap {
public static void main(String[] args) {
demo1();
TreeMap<Student, String> tm=new TreeMap<>(new Comparator<Student>() {
@Override//内部类实现比较器
public int compare(Student s1, Student s2) {
int num=s1.getName().compareTo(s2.getName());
return num==0?s1.getAge()-s2.getAge():num;
}
});
tm.put(new Student("李四",24), "上海");
tm.put(new Student("张三",33), "北京");
tm.put(new Student("王五",25), "广州");
tm.put(new Student("赵六",26), "深圳");
System.out.println(tm);
}
private static void demo1() {
TreeMap<Student, String> tm=new TreeMap<>();
tm.put(new Student("张三",23), "北京");
tm.put(new Student("李四",24), "上海");
tm.put(new Student("王五",25), "广州");
tm.put(new Student("赵六",26), "深圳");
System.out.println(tm);
}
}