Comparator and Comparable in Java - Baeldung

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

4/24/2018 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/) +

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE (/rest-with-spring-course#new-modules)

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:

1 public class Player {


2     private int ranking;
3     private String name;
4     private int age;
5      
6     // constructor, getters, setters 
7 }

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 }

Here, as expected, this results in a compile-time error:

1 The method sort(List<T>) in the type Collections


2   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 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:

1 public class Player implements Comparable<Player> {


2      
3     //...
4     @Override
5     public int compareTo(Player otherPlayer) {
6         return (this.getRanking() - otherPlayer.getRanking());
7     }
8 }

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:

1 Before Sorting : [John, Roger, Steven]


2 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 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.

4.1. Creating Comparators

To create a Comparator, we have to implement the Comparator interface.


In our rst example, we’ll create a Comparator to use the ranking attribute of Player to sort the players:

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:

1 public class PlayerAgeComparator implements Comparator<Player> {


2     @Override
3     public int compare(Player firstPlayer, Player secondPlayer) {
4        return (firstPlayer.getAge() - secondPlayer.getAge());
5     }
6 }

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:

1 PlayerRankingComparator playerComparator = new PlayerRankingComparator();


2 Collections.sort(footballTeam, playerComparator);

Now, let’s run our PlayerRankingSorter to see the result:

1 Before Sorting : [John, Roger, Steven]


2 After Sorting by ranking : [Steven, John, Roger]

If we want a di erent sorting order, we only need to change the Comparator we’re using:

1 PlayerAgeComparator playerComparator = new PlayerAgeComparator();


2 Collections.sort(footballTeam, playerComparator);

Now, when we run our PlayerAgeSorter, we can see a di erent sort order by age:

1 Before Sorting : [John, Roger, Steven]


2 After Sorting by age : [Roger, John, Steven]

4.3. Java 8 Comparators

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:

1 Comparator<Player> byRanking = Comparator


2   .comparing(Player::getRanking);
3 Comparator<Player> byAge = Comparator
4   .comparing(Player::getAge);

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).

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS (/rest-with-spring-course#new-modules)

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)

Learning to "Build your API


with Spring"?

Enter your Email Address

>> Get the eBook

  Subscribe    newest  oldest  most voted

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

Building a REST API with Spring


4?

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

JAVA “BACK TO BASICS” TUTORIAL (HTTP://WWW.BAELDUNG.COM/JAVA-TUTORIAL)


JACKSON JSON TUTORIAL (HTTP://WWW.BAELDUNG.COM/JACKSON)

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

ABOUT BAELDUNG (HTTP://WWW.BAELDUNG.COM/ABOUT/)


THE COURSES (HTTP://COURSES.BAELDUNG.COM)
CONSULTING WORK (HTTP://WWW.BAELDUNG.COM/CONSULTING)
META BAELDUNG (HTTP://META.BAELDUNG.COM/)
THE FULL ARCHIVE (HTTP://WWW.BAELDUNG.COM/FULL_ARCHIVE)
WRITE FOR BAELDUNG (HTTP://WWW.BAELDUNG.COM/CONTRIBUTION-GUIDELINES)
CONTACT (HTTP://WWW.BAELDUNG.COM/CONTACT)
COMPANY INFO (HTTP://WWW.BAELDUNG.COM/BAELDUNG-COMPANY-INFO)
#8898 (NO TITLE) (HTTP://WWW.BAELDUNG.COM/TERMS-OF-SERVICE)
PRIVACY POLICY (HTTP://WWW.BAELDUNG.COM/PRIVACY-POLICY)
EDITORS (HTTP://WWW.BAELDUNG.COM/EDITORS)
MEDIA KIT (PDF) (HTTPS://S3.AMAZONAWS.COM/BAELDUNG.COM/BAELDUNG+-+MEDIA+KIT.PDF)

http://www.baeldung.com/java-comparator-comparable 7/7

You might also like