1. Introduction
Comparisons in Java are quite easy – until they’re not.
When working with custom types, or trying to compare objects that aren’t directly comparable, we need to make use of a comparison strategy. We can build one simply, but making use of the Comparator or Comparable interfaces.
2. Setting Up the Example
Let’s take an example of a football team – where we want to line up the players by their rankings.
We’ll start by creating a simple Player class:
public class Player { private int ranking; private String name; private int age; // constructor, getters, setters }
Next, let’s create a PlayerSorter class to create our collection and make an attempt to sort it using Collections.sort:
public static void main(String[] args) { List<Player> footballTeam = new ArrayList<>(); Player player1 = new Player(59, "John", 20); Player player2 = new Player(67, "Roger", 22); Player player3 = new Player(45, "Steven", 24); footballTeam.add(player1); footballTeam.add(player2); footballTeam.add(player3); System.out.println("Before Sorting : " + footballTeam); Collections.sort(footballTeam); System.out.println("After Sorting : " + footballTeam); }
Here, as expected, this results in a compile-time error:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Player>)
Let’s understand what we did wrong here.
3. Comparable
As the name suggests, Comparable is an interface defining a strategy of comparing an object with other objects of the same type. This is called the class’s “natural ordering”.
Accordingly, in order to be able to sort – we must define our Player object as comparable by implementing the Comparable interface:
public class Player implements Comparable<Player> { //... @Override public int compareTo(Player otherPlayer) { return (this.getRanking() - otherPlayer.getRanking()); } }
The sorting order is decided by the return value of the compareTo() method.
The method returns a number indicating whether the object being compared is less than, equal to or greater than the object being passed as an argument.
Finally, when we run our PlayerSorter now, we can see our Players sorted by their ranking:
Before Sorting : [John, Roger, Steven] After Sorting : [Steven, John, Roger]
Now that we have a clear understanding of natural ordering with Comparable, let’s see how we can use other types of ordering, in a more flexible manner than directly implementing an interface.
4. Comparator
The Comparator interface defines a compare(arg1, arg2) method with two arguments which represent compared objects and works similarly to the Comparable.compareTo() method.
4.1. Creating Comparators
To create a Comparator, we have to implement the Comparator interface.
In our first example, we’ll create a Comparator to use the ranking attribute of Player to sort the players:
public class PlayerRankingComparator implements Comparator<Player> { @Override public int compare(Player firstPlayer, Player secondPlayer) { return (firstPlayer.getRanking() - secondPlayer.getRanking()); } }
Similarly, we can create a Comparator to use the age attribute of Player to sort the players:
public class PlayerAgeComparator implements Comparator<Player> { @Override public int compare(Player firstPlayer, Player secondPlayer) { return (firstPlayer.getAge() - secondPlayer.getAge()); } }
4.2. Comparators in Action
To demonstrate the concept, let’s modify our PlayerSorter by introducing a second argument to the Collections.sort method which is actually the instance of Comparator we want to use.
Using this approach, we can override the natural ordering:
PlayerRankingComparator playerComparator = new PlayerRankingComparator(); Collections.sort(footballTeam, playerComparator);
Now, let’s run our PlayerRankingSorter to see the result:
Before Sorting : [John, Roger, Steven] After Sorting by ranking : [Steven, John, Roger]
If we want a different sorting order, we only need to change the Comparator we’re using:
PlayerAgeComparator playerComparator = new PlayerAgeComparator(); Collections.sort(footballTeam, playerComparator);
Now, when we run our PlayerAgeSorter, we can see a different sort order by age:
Before Sorting : [John, Roger, Steven] After Sorting by age : [Roger, John, Steven]
4.3. Java 8 Comparators
Java 8 provides new ways of defining Comparators by using lambda expressions and the comparing() static factory method.
Let’s see a quick example of how to use a lambda expression to create a Comparator:
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
The Comparator.comparing method takes a method calculating the property that will be used for comparing items, and returns a matching Comparator instance:
Comparator<Player> byRanking = Comparator .comparing(Player::getRanking); Comparator<Player> byAge = Comparator .comparing(Player::getAge);
You can explore the Java 8 functionality in-depth in our Java 8 Comparator.comparing guide.
5. Comparator Vs Comparable
The Comparable interface is a good choice when used for defining the default ordering or, in other words, if it’s the main way of comparing objects.
Then, we must ask ourselves 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
6. Conclusion
In this tutorial, we explored the Comparable and Comparator interfaces and discussed the differences between them.
To understand more advanced topics of sorting, check out our other articles such as Java 8 Comparator, Java 8 Comparison with Lambdas.
And, as usual, the source code can be found over on Github.