按字段java排序对象的ArrayList

时间:2015-12-13 21:35:13

标签: java sorting arraylist

我有这个Student.class。我将一些学生添加到ArrayList中,然后按学生成绩对列表进行排序。如果两个学生碰巧有相同的成绩,我想用他们的名字对这两个学生进行排序,但我不知道如何。

public class Student implements Comparator<Student>, Comparable<Student> {

private String name;
private int grade;

public Student(String name, int grade) {
    this.name = name;
    this.grade = grade;
}

public Student() {
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getGrade() {
    return grade;
}

public void setGrade(int grade) {
    this.grade = grade;
}

@Override
public int compareTo(Student o) {
    return (this.name).compareTo(o.name);
}

@Override
public int compare(Student o1, Student o2) {
    return o1.grade - o2.grade;
}



public class StudentMain {

protected static List<Student> students = new ArrayList<>();

private static void loadStudents() {
    students.add(new Student("Shaggy", 3));
    students.add(new Student("Lacy", 2));
    students.add(new Student("Roger", 10));
    students.add(new Student("Tommy", 3));
    students.add(new Student("Tammy", 1));
}

public static void main(String[] args) {
    loadStudents();

    Collections.sort(students, new Student(null, 0));
    System.out.println(" ");
    for (Student s : students) {
        System.out.print(s.getName() + ", " + s.getGrade() + "\n");
    }
}

1 个答案:

答案 0 :(得分:2)

一种方法是在compare方法中实现成绩和名称比较。类似的东西:

@Override
public int compare(Student o1, Student o2) 
{
    int result = o1.grade - o2.grade;

    return (result != 0) ? result : o1.name.compareTo(o2.name);
}

另一种选择是为每个属性创建Comparator。然后,您可以使用Group Comparator混合和匹配比较器。