Comparison in Java
When camparing custom types, or objects that can’t be directly compared, we make use of Comparator
or Comparable
interfaces.
Comparable
Comparable
is an interface that can compare objects with the same type, which is called the class’s “natural ordering”.
Assume we have a player class, to enable the objects to be able to be compared
1 | public class Player implements Comparable<Player> { |
After implementing the Comparable
interface, player objects can be sorted by calling Collections.sort(playerTeam)
where playerTeam
is a collection of players.
Comparator
this interface provides a more flexible manner to sort custom items. Comparator
defines method compare(arg1, arg2)
, which works similarly to the previous compareTo
method.
Comparator
needs to be created
1 | public class playerComparator implements Comparator<Player> { |
To use this comparator, we can call
1 | Collections.sort(playerTeam, playerComparator); |
Lambda expression and comparators
1 | Comparator<Player> compareByRanking = (Player p1, Player p2) -> p1.getRanking() - p2.getRanking(); |
By the Comparator.comparing method
1 | Comparator<Player> compareByRanking = Comparator.comparing(Player::getRanking); |
Example in LeetCode 406
To compare items in a two-dimensions array by comparing their first items.
1 | // people is a 2-d array |