Comparator Interface
Implement different sort orders with the Comparator interface’s compare() method, and pass the Comparator as a parameter to List.sort(). Your implementation must explicitly handle null inputs in the compare() method to avoid a null pointer exception.
-
Comparator Example Implementation
Use the Comparator interface to impose different kinds of sorting.
The following are methods for Comparator.
-
Compares the two arguments and returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument.
Compares the two arguments and returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument.
public Integer compare(T var1, T var2)
- var1: Type: T T - The type determined by the parameterized type of the Comparator. For example, if the class implements
Comparator<Account>then var1 and var2 are of type Account . - var2: Type: T T - The type determined by the parameterized type of the Comparator. For example, if the class implements
Comparator<Account>then var1 and var2 are of type Account .
Type: Integer
Use the Comparator interface to impose different kinds of sorting.
This example implements two different ways of sorting employees.
The following example tests the implementation: