Abstract


java.lang.Comparable<T>java.util.Comparator<T>
PurposeInsert 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 Methodint 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 implements Comparable<T> that compares the Student objects based on their id
  • Second, we created a class AgeComparator that implements Comparator<T> that compares Student objects based on their age
  • Lastly, we show how Collections.Sort() uses the default comparison implemented with Comparable<T>, and how we can override it with comparison logic implemented with Comparator<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!