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
2
3
4
5
6
7
public class Player implements Comparable<Player> {
//...
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
}
}

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
2
3
4
5
6
public class playerComparator implements Comparator<Player> {
@Override
public int compare(Player player1, Player player2) {
return (player1.getRanking() - player2.getRanking());
}
}

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
2
3
4
// people is a 2-d array
Arrays.sort(people, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0]);
// The first items need to be sorted in a descending order
// The second items need to be sorted in a ascending order