Abstract
- There are two interfaces provided by Java to implement object comparison logic -
java.lang.Comparable<T>andjava.util.Comparator<T>
java.lang.Comparable<T> | java.util.Comparator<T> | |
|---|---|---|
| Purpose | Insert the comparison logic into object. | Insert comparison logic into objects that donβt implement java.lang.Comparable<T>.Overwrite objects that do implement java.lang.Comparable<T> with custom comparison logic.A OOP, so we can use AWS Lambda to insert the comparison logic as first-class citizen. |
| Comparison Method | int compareTo(T o1, T o2)Negative β Zero β Positive β | int compare(T o1, T o2)Negative β Zero β Positive β |
Important
Use
Integer.compare()to compare integers to avoid overflow. For more information, refer to Java docs.
Code Example
- First, we created a class
Studentthat implementsComparable<T>that compares theStudentobjects based on theirid - Second, we created a class
AgeComparatorthat implementsComparator<T>that comparesStudentobjects based on theirage - Lastly, we show how
Collections.Sort()uses the default comparison implemented withComparable<T>, and how we can override it with comparison logic implemented withComparator<T>
Important
Since
Comparator<T>is a Functional Interface, we can make use of Java Lambda to create a custom comparator in one line, as shown in the code editor above!
