Salesforce Apex自定义对象的排序问题 - Comparable

117 阅读1分钟

假如有一个自定义类Student,如果需要对List<Student>进行排序,是可以用Apex内置的sord方法进行排序的。

public class Student {
    public Decimal no;  // 学号
    public Decimal grade;  // 年级
}

现在如果需要按照年级降序,且同年级的学号按照升序处理:

public class Student implements Comparable {
    public Integer no;  // 学号
    public Integer grade;  // 年级
    
    public Student(Integer no, Integer grade) {
        this.no = no;
        this.grade = grade;
    }
    
    public Integer compareTo(Object compareTo) { 
        Student compareToEmp = (Student)compareTo; 
        
        // 先按照年级分类并降序
        Integer gradeCompare = compareToEmp.grade - this.grade;
        if (gradeCompare != 0) {
            return gradeCompare;
        }
        // 按照学号升序
        return this.no - compareToEmp.no;
    }
}

测试:

Student s1 = new Student(22, 1);
Student s2 = new Student(5, 1);
List<StudentCompare> lCompares = new List<StudentCompare>{s1,s2};
System.debug(lCompares);  // s1 s2
lCompares.sort();
System.debug(lCompares); // s2 s1

参考文档:Comparable Interface