按两个属性对对象排序

Sort Object by two attributes

假设我有一份学生名单:ArrayList<Student> student = new ArrayList<>();。 Student-class 看起来像这样:

public class Student {
    String name;
    int age;
    String hobby;

    //getter and Setter methods below
}

我想按姓名对列表进行排序,但如果姓名相同,我想按年龄排序。我怎样才能在 Java.

中做到这一点

有了这个我已经可以按名称排序了:

public class MyComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        if(o1.getName() > o2.getName()){
            return 1;
        }
        else if(o1.getName() < o2.getName())
        {
            return -1;
        }
        else{
            return 0;
        }
    }
}

所以如果他们有相同的名字,我该如何在年龄之后排序? 最后我想Collections.sort(student, MyComparator comp)对列表进行排序。

这应该有效:

public class StudentsComparator implements Comparator<Student> {

    @Override
    public int compare(Student s1, Student s2) {
        final int nameComparison = s1.getName().compareToIgnoreCase(s2.getName());
        if (nameComparison != 0) {
            return nameComparison;
        }
        return Integer.compare(s1.getAge(), s2.getAge());
    }

}

你也可以让Student具有可比性:

public class Student implements Comparable<Student> {

    String name;
    int age;
    String hobby;

    @Override
    public int compareTo(Student other) {
        final int nameComparison = name.compareToIgnoreCase(other.name);
        if (nameComparison != 0) {
            return nameComparison;
        }
        return Integer.compare(age, other.age);
    }

}