Saturday, April 25, 2020

Comparable Interface in Salesforce

The Comparable interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.

To add List sorting support for your Apex class, you must implement the Comparable interface with its compareTo method in your class.

When a class implements the Comparable interface it has to implement a method called compareTo(). This method returns an integer value that is the result of the comparison.

compareTo(objectToCompareTo)
Returns an integer value that is the result of the comparison.

The implementation of this method returns the following values:

0 if this instance and objectToCompareTo are equal
> 0 if this instance is greater than objectToCompareTo
< 0 if this instance is less than objectToCompareTo

If this object instance and objectToCompareTo are incompatible, a System.TypeException is thrown.

Example:
global class Employee implements Comparable {

    public Long id;
    public String name;
    public String phone;
    
    // Constructor
    public Employee(Long i, String n, String p) {
        id = i;
        name = n;
        phone = p;
    }
    
    // Implement the compareTo() method
    global Integer compareTo(Object compareTo) {
        Employee compareToEmp = (Employee)compareTo;
        if (id == compareToEmp.id) return 0;
        if (id > compareToEmp.id) return 1;
        return -1;        
    }
}

Sort the List using compareTo(object) method.
List<Employee> empList = new List<Employee>();
empList.add(new Employee(101,'Joe Smith', '4155551212'));
empList.add(new Employee(101,'J. Smith', '4155551212'));
empList.add(new Employee(25,'Caragh Smith', '4155551000'));
empList.add(new Employee(105,'Mario Ruiz', '4155551099'));

// Sort using the custom compareTo() method
empList.sort();

// Write list contents to the debug log
for (Employee emp : empList){
 system.debug(emp);
}

Output


No comments:

Post a Comment