Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code used in "Apex List Comparator | System.ListException: One or more of the items in this list is not Comparable" tutorial on SFDC Stop (https://youtu.be/Sf95Bl_zP2U)
---------------------------------------------------------------------------------------------------------------------------
Custom Comparator
---------------------------------------------------------------------------------------------------------------------------
List<Integer> numbers = new List<Integer>{ 5, 3, 2, 1, 4 };
System.debug('Initial list of Integers => ' + numbers);
System.debug('Sorting Integers....');
numbers.sort();
System.debug('Final list of Integers =>' + numbers);
System.ListException: One or more of the items in this list is not Comparable.
---------------------------------------------------------------------------------
class Employee implements Comparable {
Integer id;
String name;
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer compareTo(Object anotherObject) {
Employee secondEmployee = (Employee) anotherObject;
// if( id > secondEmployee.id ) {
// return -1;
// } else if( id < secondEmployee.id ) {
// return 1;
// }
if( name < secondEmployee.name ) {
return -1;
} else if( name > secondEmployee.name ) {
return 1;
}
return 0;
}
}
List<Employee> employees = new List<Employee>();
employees.add(new Employee(1, 'Richard Hendricks'));
employees.add(new Employee(5, 'Gilfoyle'));
employees.add(new Employee(3, 'Dinesh'));
employees.add(new Employee(2, 'Monica'));
employees.add(new Employee(4, 'Erlich Bachman'));
System.debug('Initial List: ');
System.debug(employees);
System.debug('Sorting Employees....');
employees.sort();
System.debug('Sorted List: ');
System.debug(employees);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment