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.
Code Example
- First, we created a class
Student
that implementsComparable<T>
that compares theStudent
objects based on theirid
- Second, we created a class
AgeComparator
that implementsComparator<T>
that comparesStudent
objects 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!