Skip to content
Aasim's Web Corner
Aasim's Web Corner

Ink is better than the best memory.

  • Odysseys & Artistry
    • Saunterer Soul
    • My Poetry
    • My Sketch Work
  • Project Management
    • Agile & Frameworks
    • PMP Certification
  • Digital Diary
    • History
    • Islam
    • Life Around Us
    • My Bookshelf
  • My Tutorials
    • Amazon Kindle
    • Android
    • Aspect Oriented Programming
    • BlackBerry
    • Code Repositories
    • iOS
    • Java
    • JavaScript
    • Linux
    • Random Tips
Connect with me
Aasim's Web Corner

Ink is better than the best memory.

Java Sorting - Comparator vs Comparable - AasimNaseem.com

Java Sorting – Comparator vs Comparable

Aasim Naseem, September 20, 2010 | Read Count: 15,493May 5, 2025
Category: My Tutorials > Java

Hello All …
I hope everyone is in good health and enjoying Allah Almighty’s blessings.
I was working on a task where I needed to sort a collection (list) of objects on the basis of some attribute within a single element of that list. Though I have used comparators many times in applications, today was the first time I wrote my first comparator and sorted a list using Collection.sort(listName, comparatorClass). Sharing this knowledge with you people too.

What are Java Comparators and Comparables?  As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order.

Two of these concepts can be explained as follows.

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Do we need to compare objects? The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.

How to use these?

There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;

java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.

  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1

java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.

  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o1

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.

public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}

Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.

import java.util.*;

public class Util {

    public static List<Employee> getEmployees() {

        List<Employee> col = new ArrayList<Employee>();

        col.add(new Employee(5, "Frank", 28));
        col.add(new Employee(1, "Jorge", 19));
        col.add(new Employee(6, "Bill", 34));
        col.add(new Employee(3, "Michel", 10));
        col.add(new Employee(7, "Simpson", 8));
        col.add(new Employee(4, "Clerk",16 ));
        col.add(new Employee(8, "Lee", 40));
        col.add(new Employee(2, "Mark", 30));

        return col;
    }
}

Sorting in natural ordering

Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.

public class Employee implements Comparable<Employee> {
    private int empId;
    private String name;
    private int age;

    /**
     * Compare a given Employee with this object.
     * If employee id of this object is
     * greater than the received object,
     * then this object is greater than the other.
     */
    public int compareTo(Employee o) {
        return this.empId - o.empId ;
    }
    ….
}

The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.

We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.

import java.util.*;

public class TestEmployeeSort {

    public static void main(String[] args) {
        List coll = Util.getEmployees();
        Collections.sort(coll); // sort method
        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}
EmpId Name  Age
1    Jorge   19
2    Mark    30
3    Michel  10
4    Clerk   16
5    Frank   28
6    Bill    34
7    Simp     8
8    Lee     40

Sorting by other fields

If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.

By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.
Sorting by name field
Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.

public class EmpSortByName implements Comparator<Employee>{

    public int compare(Employee o1, Employee o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).

Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).

Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.

import java.util.*;

public class TestEmployeeSort {

    public static void main(String[] args) {

        List coll = Util.getEmployees();
        //Collections.sort(coll);
        //use Comparator implementation
        Collections.sort(coll, new EmpSortByName());
        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}

Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.

EmpId Name Age

6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8

Sorting by empId field
Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class
does that.

public class EmpSortByEmpId implements Comparator<Employee>{

    public int compare(Employee o1, Employee o2) {
        return o1.getEmpId().compareTo(o2.getEmpId());
    }
}

 

Explore further

Do not stop here. Work on the followings by yourselves and sharpen knowledge on these concepts.

  1. Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
  2. Explore how & why equals() method and compare()/compareTo() methods must be consistence.

If you have any issues on these concepts; please add those in the comments section and we’ll get back to you.

free counters

Author Profile

Aasim Naseem
Hey, Thanks for your interest. I’m a PMP, AWS Solutions Architect, and Scrum Master certified professional with 17+ years of hands-on experience leading projects, building teams, and helping organizations deliver software solutions better, faster, and smarter.

Outside of work, I’ve got a deep curiosity for history — especially ancient civilizations like Egypt. I also enjoy reflecting on the everyday moments that shape how we live and work. This blog is my space to share insights, lessons, and thoughts from both my professional journey and personal interests.

Thanks for reading — and I hope you will find something here that matches your interest.
Latest entries
  • Economic impact of Eid ul Adha - AasimNaseem.comIslamJune 6, 2025 | Read Count: 282Economic impact of Eid-ul-Adha
  • Best PMP Exam Study Resources - AasimNaseem.comPMP CertificationMay 23, 2025 | Read Count: 493Best PMP Study Resources for 2025 (Books, Courses, Tools & More)
  • agile vs scrum - AasimNaseem.comAgile & FrameworksMay 7, 2025 | Read Count: 463Agile vs Scrum: Finally Understanding the Difference
  • When Agile shouldn’t Use - AasimNaseem.comAgile & FrameworksApril 25, 2025 | Read Count: 493When Not To Use Agile: 5 Signs You Need a Different Approach
Java ComparableComparatorComparator vs ComparablecompareTo()Java Sortingjava.lang.Comparable: int compareTo(Object o1)java.util.Comparator: int compare(Object o1Objecto2)

Post navigation

Previous post
Next post

Related Posts

Java JavaDateFormatting-AasimNaseem.com

Date Formatting in Java

August 13, 2010 | Read Count: 15,468May 5, 2025

Category: My Tutorials > JavaHi all… Hope you’re enjoying your time… Today I will explain how to use date-time (date manipulation) in the Java programming language. I was working on a task where I needed to play with time/date. In my other post, I explained the date formatting in C#. Today you…

Read More
Java Java 1.7 G1 Garbage Collector - AasimNaseem.com

Java 1.7 G1 Garbage Collector

November 3, 2011 | Read Count: 14,496May 5, 2025

Category: My Tutorials > JavaHi all, Hope everything is going good at your desks; Last night, I was reading new features in Java 1.7 and found some updates in garbage collection mechanism; There are many updates in 1.7 ranges from core vm, i18n, Nimbus for Swings and other enhancements. We…

Read More
Java G1: Java's Garbage First Garbage Collector

G1: Java’s Garbage First Garbage Collector

October 1, 2009 | Read Count: 16,498May 5, 2025

Category: My Tutorials > JavaA garbage collector works to reclaim areas of memory within an application that will never be accessed again At JavaOne 2009, Sun released Java SE 6 Update 14, which included a version of the much-anticipated Garbage First (G1) garbage collector. G1 is a low-pause, low-latency, sometimes…

Read More

Comments (12)

  1. devs says:
    September 24, 2010 at 2:20 am

    boom chica wowow

    Reply
  2. potenzmittel shop says:
    October 2, 2010 at 11:28 pm

    Simply discovered your web page through Yahoo and I consider this can be a disgrace that you are not ranked more due to the fact that that is a Great post. To switch this I determined to avoid wasting your Blog to my RSS reader and I will try to point out you in one of my posts since you actually deserv extra readers when publishing content material of this high quality.

    Reply
  3. Laurbarlsab says:
    October 5, 2010 at 5:02 am

    looking for seo services ? validate out our website templates and acquire your own falsh website through despite available today, huge electing of unchained flash templates for you online, profuse brand-new designs with ir without flash.
    so choose your free flash template from the larget flash templates selection. so get your free website templates now and build your free website . visit the latest online casino games. vs the all new casino games guide. looking for sex ? or new casino games ? Amex Casino . few more amex casino sites.
    online blackjack .

    Reply
  4. free movies online says:
    October 6, 2010 at 5:38 pm

    Top site, I had not noticed aasims.wordpress.com previously during my searches!
    Continue the excellent work!

    Reply
  5. Arerbruth says:
    October 6, 2010 at 9:16 pm

    t’s such a great site. fanciful, very fascinating!!!

    ——-

    Reply
  6. saiful103a says:
    October 12, 2010 at 8:59 pm

    Your blog is really great.I will explore it more in future since i am interested in blackberry application development. i really liked your blog

    Reply
  7. New Credit File says:
    October 14, 2010 at 2:33 am

    I have been back here 3 times now and am absolutely loving the energy on this discussion. Thanks for a fantastic outlet to read top quality information.

    Reply
  8. pc games says:
    October 20, 2010 at 11:41 am

    You made some good points there. I did a search on the topic and found most people will agree with
    your blog.

    Reply
  9. pc games says:
    October 20, 2010 at 1:55 pm

    Lovely sharp post. Never thought that it was this easy. Extolment to you!

    Reply
  10. james says:
    December 5, 2010 at 4:30 pm

    Great story on another page and didn’t quite get it. Your post helped me understand it better.

    Reply
  11. Upender says:
    November 18, 2011 at 12:11 pm

    Nice….good post.
    Really useful.

    Reply
  12. Ashutosh says:
    October 1, 2013 at 4:44 pm

    why r these people putting allah everywhere …… what u have wriiten here for java it is fabulous but is it neccessary to put allah and all that… here in the starting of solution.. thing beyond allah and all this ……

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Economic impact of Eid-ul-Adha
    Economic impact of Eid-ul-Adha
    June 6, 2025 | Read Count: 282
  • Best PMP Study Resources for 2025 (Books, Courses, Tools & More)
    Best PMP Study Resources for 2025 (Books, Courses, Tools & More)
    May 23, 2025 | Read Count: 493
  • Agile vs Scrum: Finally Understanding the Difference
    Agile vs Scrum: Finally Understanding the Difference
    May 7, 2025 | Read Count: 463
  • When Not To Use Agile: 5 Signs You Need a Different Approach
    When Not To Use Agile: 5 Signs You Need a Different Approach
    April 25, 2025 | Read Count: 493
  • Quran on Peace and Kindness
    Quran on Peace and Kindness
    April 20, 2025 | Read Count: 452

Posts from Past

  • June 2025
  • May 2025
  • April 2025
  • January 2025
  • November 2024
  • April 2024
  • October 2022
  • August 2021
  • September 2020
  • May 2020
  • April 2019
  • January 2019
  • September 2018
  • July 2015
  • June 2015
  • November 2014
  • September 2014
  • April 2014
  • June 2013
  • May 2013
  • February 2013
  • January 2013
  • December 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • March 2012
  • February 2012
  • January 2012
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009

Categories List

  • Agile & Frameworks
  • Amazon Kindle
  • Android
  • Aspect Oriented Programming
  • BlackBerry
  • Blog
  • Code Repositories
  • History
  • iOS
  • Islam
  • Java
  • JavaScript
  • Life Around Us
  • Linux
  • My Bookshelf
  • My Poetry
  • My Sketch Work
  • PMP Certification
  • Random Tips
  • Saunterer Soul

Recent Posts

  • Economic impact of Eid-ul-Adha
  • Best PMP Study Resources for 2025 (Books, Courses, Tools & More)
  • Agile vs Scrum: Finally Understanding the Difference
  • When Not To Use Agile: 5 Signs You Need a Different Approach
  • Quran on Peace and Kindness

Recent Comments

  1. Aasim Naseem on When Not To Use Agile: 5 Signs You Need a Different Approach
  2. Aasim Naseem on When Not To Use Agile: 5 Signs You Need a Different Approach
  3. Masjid Wazir Khan, Lahore Pakistan - Aasim's Web Corner on Everlasting Art of Badshahi Masjid Lahore Pakistan
  4. Rishi Kumar on When Not To Use Agile: 5 Signs You Need a Different Approach
  5. Best PMP Study Resources for 2025 (Books, Courses, Tools & More) - Aasim's Web Corner on PMP Exam Eligibility 2025: 3 Things You Need to Know
©2025 Aasim's Web Corner | WordPress Theme by SuperbThemes