Created
December 4, 2021 15:11
-
-
Save rahulmalhotra/d3d4919c11ff9faf18e79ba703550456 to your computer and use it in GitHub Desktop.
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------------------------------------------------------------------------------------------------------------------- | |
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