Apex Comparator Interface

How to compare custom classes easily?

Thankfully, in Winter ‘24 Apex got similar interface that we can use with Lists!

If you came from Java, you probably miss this useful interface:

apex
java.util
Interface Comparator<T>

Thankfully, in Winter ‘24 Apex got similar interface that we can use with Lists!

apex
Comparator<Account>

Okay, and how to use it?

It's fairly simple, let's start with something we can compare, like student grades:

apex
public class Student {
    public String name;
    public Integer grade;

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

Now we need comparator implementation:

apex
public class GradesAscCompare implements Comparator<Student> {
    public Integer compare(Student s1, Student s2) {
        if (s1.grade == s2.grade) {
            return 0;
        }

        return s1.grade > s2.grade ? 1 : -1;
    }
}

We can do it as a standalone class like above, or a collection of different comparators for our use case:

apex
public class StudentComparators {
    public class GradesAscCompare implements Comparator<Student> {
        public Integer compare(Student s1, Student s2) {
            if (s1.grade == s2.grade) {
                return 0;
            }

            return s1.grade > s2.grade ? 1 : -1;
        }
    }

    public class GradesDscCompare implements Comparator<Student> {
        public Integer compare(Student s1, Student s2) {
            if (s1.grade == s2.grade) {
                return 0;
            }

            return s1.grade < s2.grade ? 1 : -1;
        }
    }
}

Okay, but what does this code mean?

As you can see, the compare method returns three values: -1, 0, 1. Each of those values corresponds to one of the comparison results: -1 lesser than 0 equal to 1 greater than

So when we try to compare four students with following grades [5, 2, 3, 5] we will get those comparison results:

compare(5, 2) compare(5, 3) compare(5, 5) compare(2, 5) compare(2, 3) … and so on

How it works in our example?

Test code:

apex
List<Student> students = new List<Student>{
    new Student('a', 5),
    new Student('b', 2),
    new Student('c', 3),
    new Student('d', 5)
};

students.sort(new StudentComparators.GradesAscCompare());
System.debug(students);

students.sort(new StudentComparators.GradesDscCompare());
System.debug(students);

Results:

bash
|DEBUG|Grades ascending: ({ Student b - Grade: 2}, { Student c - Grade: 3}, { Student a - Grade: 5}, { Student d - Grade: 5})
|DEBUG|Grades descending: ({ Student a - Grade: 5}, { Student d - Grade: 5}, { Student c - Grade: 3}, { Student b - Grade: 2})

Text and code were extracted from the original slide. Plain-text version of the whole catalog