Member-only story
Quick tutorial: writing a comparator in Java
Computers are constantly sorting things for us. Shopping results by price from lowest to highest. Athletes by one stat or another. Movies by rating on Rotten Tomatoes, to give just a few examples.
These are examples of people and things with no natural ordering. They can be sorted by many different criteria, with no particular criterion showing itself to be any more obvious than another.
Often the sorting criteria are things that do have natural ordering. Like for example, batting averages are numbers that are quite naturally sorted in ascending or descending order, whereas the baseball players those batting averages belong to could be sorted by several other criteria, such as last name, number on his or her uniform shirt, date of joining the team, etc.
When writing a Java program, a data type T
that has natural ordering should generally conform to the Comparable<T>
interface. Examples include String
and LocalDate
, as well as primitive wrappers like Integer
and Double
.
But if a data type T
doesn’t have natural ordering and we need to sort its instances by one criterion or another, we can define comparators according to that particular criterion.
A comparator conforms to the Comparator<T>
interface in the java.util
package. In that same package, we can find plenty of…