Java Comparator Methods
A comparator is an object that decides which of two objects should come first. Pass it to a sorting method, like list.sort() or Collections.sort(), to sort a list in your own order, for example cars by year.
Import java.util.Comparator to use it. You can write the sorting rule yourself with a lambda expression (a short block of code that works like a method), or let methods like comparing() create the comparator for you. In the tables, T means the type of the objects to compare, like String or Car.
Comparator Methods
The compare() method is the sorting rule that every comparator has. The static methods (methods that you call on the interface name) comparing(), comparingInt(), naturalOrder() and reverseOrder() create a new comparator, for example Comparator.comparing(c -> c.brand). You call reversed() and thenComparing() on a comparator, to get a new comparator from it.
| Method | Description | Return Type |
|---|---|---|
| compare() | Compares two objects and returns a number that shows which one should come first | int |
| comparing() | Returns a comparator that sorts objects by a value that you choose, like the brand of a car | Comparator<T> |
| comparingInt() | Returns a comparator that sorts objects by an int value, like the year of a car | Comparator<T> |
| naturalOrder() | Returns a comparator that sorts objects in their natural order, like A to Z for strings | Comparator<T> |
| reversed() | Returns a comparator that sorts in the opposite order of this comparator | Comparator<T> |
| reverseOrder() | Returns a comparator that sorts objects in the reverse of their natural order, like Z to A for strings | Comparator<T> |
| thenComparing() | Returns a comparator with a second sorting rule, used when the first rule finds two objects equal | Comparator<T> |
Comparable Methods
A class that implements the Comparable interface can compare itself with other objects of the same class, with its compareTo() method. This gives the objects a natural order (their default order), so a list of them can be sorted with Collections.sort() without a comparator. String and Integer are examples of classes that implement Comparable.
| Method | Description | Return Type |
|---|---|---|
| compareTo() | Compares this object with another object and returns a number that shows which one should come first | int |
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial