Comparator and Comparable in Java - Baeldung
Comparator and Comparable in Java - Baeldung
(http://baeldung.com)
Comparator and
Comparable in Java
Last modi ed: February 20, 2018
by baeldung (http://www.baeldung.com/author/baeldung/)
Java (http://www.baeldung.com/category/java/) +
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.
Next, let’s create a PlayerSorter class to create our collection and make an attempt to sort it using Collections.sort:
http://www.baeldung.com/java-comparator-comparable 1/7
4/24/2018 Comparator and Comparable in Java | Baeldung
1 public static void main(String[] args) {
2 List<Player> footballTeam = new ArrayList<>();
3 Player player1 = new Player(59, "John", 20);
4 Player player2 = new Player(67, "Roger", 22);
5 Player player3 = new Player(45, "Steven", 24);
6 footballTeam.add(player1);
7 footballTeam.add(player2);
8 footballTeam.add(player3);
9
10 System.out.println("Before Sorting : " + footballTeam);
11 Collections.sort(footballTeam);
12 System.out.println("After Sorting : " + footballTeam);
13 }
3. Comparable
As the name suggests, Comparable is an interface de ning 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 de ne our Player object as comparable by implementing the Comparable
interface:
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:
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 exible manner than directly implementing an interface.
4. Comparator
The Comparator interface de nes a compare(arg1, arg2) method with two arguments which represent compared objects and
works similarly to the Comparable.compareTo() method.
http://www.baeldung.com/java-comparator-comparable 2/7
4/24/2018 Comparator and Comparable in Java | Baeldung
1 public class PlayerRankingComparator implements Comparator<Player> {
2
3 @Override
4 public int compare(Player firstPlayer, Player secondPlayer) {
5 return (firstPlayer.getRanking() - secondPlayer.getRanking());
6 }
7 }
Similarly, we can create a Comparator to use the age attribute of Player to sort the players:
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:
If we want a di erent sorting order, we only need to change the Comparator we’re using:
Now, when we run our PlayerAgeSorter, we can see a di erent sort order by age:
Java 8 provides new ways of de ning 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:
1 Comparator<Player> byRanking
2 = (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:
You can explore the Java 8 functionality in-depth in our Java 8 Comparator.comparing (http://www.baeldung.com/java-8-
comparator-comparing) guide.
http://www.baeldung.com/java-comparator-comparable 3/7
4/24/2018 Comparator and Comparable in Java | Baeldung
5. Comparator Vs Comparable
The Comparable interface is a good choice when used for de ning 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 de ne multiple di erent comparison strategies which isn’t possible when using Comparable
6. Conclusion
In this tutorial, we explored the Comparable and Comparator interfaces and discussed the di erences between them.
To understand more advanced topics of sorting, check out our other articles such as Java 8 Comparator
(http://www.baeldung.com/java-8-comparator-comparing), Java 8 Comparison with Lambdas (http://www.baeldung.com/java-
8-sort-lambda).
And, as usual, the source code can be found over on Github (https://github.com/eugenp/tutorials/tree/master/core-java).
http://www.baeldung.com/java-comparator-comparable 4/7
4/24/2018 Comparator and Comparable in Java | Baeldung
(http://www.baeldung.com/wp-content/uploads/2016/05/baeldung-rest-post-footer-main-
1.2.0.jpg)
(http://www.baeldung.com/wp-
content/uploads/2016/05/baeldung-
rest-post-
footer-icn-
1.0.0.png)
JoeHx (https://hendrixjoseph.github.io/)
One confusing thing that occasionally happens to me is when my compactor gives me an “IllegalArgumentException: Comparison
method violates its general contract!” – while I understand what it happening in the abstract (there’s a situation where A > B > C
Guest
but A !> C) it can be di cult to nd exactly how.
1 4 months ago
Me (http://www.baeldung.com/author/thefather/)
(http://www.baeldung.com/author/thefather/)
Hey Joe – if you can reproduce that in a test, don’t hesitate to open an issue – I’ll be happy to have a look and
Admin
potentially update the article.
0 4 months ago
http://www.baeldung.com/java-comparator-comparable 5/7
4/24/2018 Comparator and Comparable in Java | Baeldung
Download
The E-book
Email Address
Download
CATEGORIES
SPRING (HTTP://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTP://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTP://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTP://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTP://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTP://WWW.BAELDUNG.COM/CATEGORY/JACKSON/)
HTTPCLIENT (HTTP://WWW.BAELDUNG.COM/CATEGORY/HTTP/)
KOTLIN (HTTP://WWW.BAELDUNG.COM/CATEGORY/KOTLIN/)
SERIES
http://www.baeldung.com/java-comparator-comparable 6/7
4/24/2018 Comparator and Comparable in Java | Baeldung
HTTPCLIENT 4 TUTORIAL (HTTP://WWW.BAELDUNG.COM/HTTPCLIENT-GUIDE)
REST WITH SPRING TUTORIAL (HTTP://WWW.BAELDUNG.COM/REST-WITH-SPRING-SERIES/)
SPRING PERSISTENCE TUTORIAL (HTTP://WWW.BAELDUNG.COM/PERSISTENCE-WITH-SPRING-
SERIES/)
SECURITY WITH SPRING (HTTP://WWW.BAELDUNG.COM/SECURITY-SPRING)
ABOUT
http://www.baeldung.com/java-comparator-comparable 7/7