Basic Comparator
The Comparable interface is a good choice to use for defining the default ordering, or in other words, if it's the main way of comparing objects. So why use a Comparator if we already have Comparable?
There are several reasons why: - Sometimes we can't modify the source code of the class whose objects we want to sort, thus making the use of Comparable impossible - Using Comparators allows us to avoid adding additional code to our domain classes - We can define multiple different comparison strategies, which isn't possible when using Comparable
public class Player implements Comparable<Player> {
@Override
public int compareTo(Player otherPlayer) {
return Integer.compare(getRanking(), otherPlayer.getRanking());
}
}
| If the comparison returns | Then ... |
|---|---|
| >= 1 | this.rank > other.rank |
| 0 | this.rank == other.rank |
| <= -1 | this.rank < other.rank |
public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return Integer.compare(firstPlayer.getRanking(), secondPlayer.getRanking());
}
}
Lambda
Comparator<Player> comparator = (p1, p2) -> p1.getRanking() - p2.getRanking();