天天看点

TreeMap中如何实现自定义类key值的排序

在TreeMap中,如果key值是java中的基本类型,TreeMap会自身帮我们排序,如果是自定义类型,如定义一个Student类作为key值,我们如果不告知排序规则的话,运行就会报错。所以,如何实现自定义排序呢?解决方案有2个,二者选一即可:

  • 在Student类中实现Comparable,重写compareTo方法
  • 在构造函数中new Comparator,匿名内部类,重写compare 方法

代码如下:

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student() {
        super();
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }

    @Override
    public int compareTo(Student o) {
        int num1 = this.getAge()-o.getAge();
        int num2 = num1==?this.getName().compareTo(o.getName()):num1;
        return num2;
    }
           
public class TestTreeMap {
    public static void main(String[] args) {
        //1.创建集合
        TreeMap<Student, String> map = new TreeMap<Student, String>(new Comparator<Student>() {
            //按照年龄来排序,年龄相同按照姓名来排序
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getAge()==o2.getAge()){
                    return o1.getName().compareTo(o2.getName());
            }
            return o1.getAge()-o2.getAge();
            }
        //2.创建学生对象并往集合中增加
        Student s1 = new Student("张三",);
        Student s2 = new Student("李四",);
        Student s3 = new Student("王五",);
        Student s4 = new Student("张三",);
        map.put(s1, "2001");
        map.put(s2, "2002");
        map.put(s3, "2003");
        map.put(s4, "2004");

        //3.遍历集合 ,排序完成
        Set<Student> set = map.keySet();
        for(Student student : set){
            String value = map.get(student);
            System.out.println(student.getName()+"=="+student.getAge()+"=="+value);
        }
    }
}