• Chennai, Bangalore & Online: 93450 45466Coimbatore: 95978 88270Madurai: 97900 94102

  • Comparable and Comparator Interfaces In Java: Differences and their use case



    In java, the behaviour of a class is specified by the implemented interface.There are two such interfaces as follows:

    Comparable in Java
    Comparator in Java

    For example consider you have an Employee class, with attributes as salary, days worked, name, bonus earned etc., and now to sort the list of employees based on the number of working days you can use Comparable and Comparator interface to arrange the list.

    Comparator is used to sort objects based on the different attributes of different objects using the data members of the class, whereas Comparable is used to sort objects in a natural ordering using the data members of the class.So Let us understand these interfaces with examples and their use cases in this sequence,

    What is comparable In Java
    Using CompareTo Method In Java
    Java Comparable Example
    What is Comparator In Java
    How to implement Comparator In Java?
    Java Comparable V/s Comparator
    Let us dive deep in to each of these topics one by one starting with..

    What is comparable In Java

    Comparable is used to sort objects in a natural ordering using the data members of the class.It compares one object with the other(itself) on the basis of single data member or attribute.The comparable interface is found at the java.lang. Comparable and have only one method, CompareTo(Object) which is responsible for sorting.

    Let us now understand what is the CompareTo() method of Comparable in Java. What is the CompareTo() method In Java and how to use CompareTo()

    The CompareTo() method is used to compare the current (this reference) object with the other(given) object.The CompareTo() method can sort the objects of the following types:

    String objects
    Wrapper class objects
    User-defined class objects

    This method returns an integer value, a positive, a negative or a zero on the basis of comparison result.Here is how the result is decided

    positive integer: if the current object is greater than the given or specified object (lexicographically in case of Strings),it returns a positive number.
    negative integer: if the current object is less than the given or specified object(lexicographically in case of Strings), it returns a negative number.
    zero: if the current object is equal to the given or specified object(lexicographically in case of Strings), it returns zero.
    Let us understand the comparable interface for sorting with an example problem. Java Comparable Example A java program to compare working from the year of different employees.
    
    // A Java program to demonstrate use of Comparable interface
    
    import java.io.*;
    
    import java.util.*;
    
    // A class 'Employees' that implements Comparable
    
    class Employees implements Comparable<Employees> {
    
    private int year;
    
    private String name;
    
    private double salary;
    
    private String position;
    
     
    
    // Used to sort employees by working year
    
    public int compareTo(Employees e) {
    
    return this.year - e.year;
    
    }
    
     
    
    // Constructor
    
    public Employees(String nm, int yr, double sal, String pos) {
    
    this.name = nm;
    
    this.year = yr;
    
    this.salary = sal;
    
    this.position = pos;
    
    }
    
     
    
    // Getter methods for accessing private data members
    
    public int worksince() {
    
    return year;
    
    }
    
     
    
    public String getname() {
    
    return name;
    
    }
    
     
    
    public double getsalary() {
    
    return salary;
    
    }
    
     
    
    public String getposition() {
    
    return position;
    
    }
    
    }
    
     
    
    // Driver class
    
    class Main {
    
    public static void main(String[] args) {
    
    ArrayList<Employees> list = new ArrayList<Employees>();
    
     
    
    // adding few employees to the list
    
    list.add(new Employees("Adam Smith", 2007, 60000.00, "Software Developer"));
    
    list.add(new Employees("Atufa Shireen", 2019, 40000.00, "Software Developer"));
    
    list.add(new Employees("John Lewis", 2020, 35000.00, "Business Analyst"));
    
    list.add(new Employees("Dove Carson", 2016, 45000.00, "Research Analyst"));
    
    list.add(new Employees("Sofia Cameroon", 2016, 45000.00, "Research Analyst"));
    
     
    
    Collections.sort(list);
    
     
    
    System.out.println("Employees after sorting based on salary: ");
    
    for (Employees Employee : list) {
    
    System.out.println(Employee.getname() + ", working as a: " + Employee.getposition() + ", since the year: "
    
    + Employee.worksince() + " Salary: " + Employee.getsalary());
    
    }
    
    }
    
    }
    

    In the above example program, I created a class for Employees, with their salaries, names, position, and working since(year). The Class Employees is implementing the Comparable interface and overrides the compareTo method. This method sorts the instances of the Student class, based on their year of working, invoked by the sort method.

    Output for the above program will be as follows
    
    Employees after sorting based on salary:
    
    Adam Smith, working as a: Software Developer, since the year: 2007 Salary: 60000.0
    
    Dove Carson, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Sofia Cameroon, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Atufa Shireen, working as a: Software Developer, since the year: 2019 Salary: 40000.0
    
    John Lewis, working as a: Business Analyst, since the year: 2020 Salary: 35000.0
    

    Check out this Complete Online Java Course by FITA. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real time applications using Servlets, Hibernate Framework, and Spring with Aspect Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, to make you an industry required certified java developer.

    Now that we have covered the Comparable Interface with an example for sorting objects, we will now see the Comparator interface of Java.

    Comparator interface In Java

    The Comparator interface is used to sort the objects of a user defined class by comparing one object with the other of the same type. Moreover, it sorts the objects which have the self tendency to sort themselves. The Comparator interface is present at java.util.Comparator.

    Unlike Comparable, the Comparator uses two methods for sorting,
    compare(Object obj1,Object obj2)
    equals(Object element)
    The compare(Object obj1, Object obj2), compares the two passed parameters with each other and returns,
    Negative integer, if the first argument is less than the second argument
    A positive integer, if the first argument is greater than the second argument and
    Zero, if both the arguments are equal.

    The second method equals(Object element), takes one positional argument as Object, and compares the given Object with the comparator.

    equals() method will return true if the passed object is also a comparator else returns false.

    The sort() method of the Collections class, takes comparator and invokes or calls the compare method of the Comparator interface for sorting the objects.

    The following steps are followed for sorting objects, with a comparator
    Create a class and implement Comparable class on it
    Make an instance of that class
    Override the compare or compareTo method
    Overload and invoke the sort method by passing the list and the instance of class(which implements comparable).

    After discussing the Comparators in Java, it is the time to implement it in an example program.

    
     //A Java program to demonstrate Comparator interface
    
    import java.io.*;
    
    import java.util.*;
    
     
    
    // A class 'Employees' that implements Comparable
    
    class Employees implements Comparable<Employees> {
    
    private double salary;
    
    private String name;
    
    private int year;
    
    private String position;
    
     
    
    // Sorting Employees by the working experience
    
    public int compareTo(Employees e) {
    
    return this.year - e.year;
    
    }
    
     
    
    // Constructor for the Employees class
    
    public Employees(String nm,int yr,double sal, String pos) {
    
    this.name = nm;
    
    this.salary = sal;
    
    this.year = yr;
    
    this.position = pos;
    
    }
    
     
    
    // Getter methods for accessing private data members
    
    public double getsalary() {
    
    return salary;
    
    }
    
     
    
    public String getname() {
    
    return name;
    
    }
    
     
    
    public int worksince() {
    
    return year;
    
    }
    
     
    
    public String getposition() {
    
    return position;
    
    }
    
    }
    
    // Class for comparing employees by salary
    
    class salaryCompare implements Comparator<Employees> {
    
    public int compare(Employees e1, Employees e2) {
    
    if (e1.getsalary() < e2.getsalary())
    
    return -1;
    
    if (e1.getsalary() > e2.getsalary())
    
    return 1;
    
    else
    
    return 0;
    
    }
    
    }
    
     
    
    // Class to compare employees by name
    
    class NameCompare implements Comparator<Employees> {
    
    public int compare(Employees e1, Employees e2) {
    
    return e1.getname().compareTo(e2.getname());
    
    }
    
    }
    
     
    
    // Driver class
    
    class Main {
    
    public static void main(String[] args) {
    
    ArrayList<Employees> list = new ArrayList<Employees>();
    
    // adding few employess to the list
    
    list.add(new Employees("Adam Smith", 2007, 60000.00, "Software Developer"));
    
    list.add(new Employees("Atufa Shireen", 2019, 40000.00, "Software Developer"));
    
    list.add(new Employees("John Lewis", 2020, 35000.00, "Business Analyst"));
    
    list.add(new Employees("Dove Carson", 2016, 45000.00, "Research Analyst"));
    
    list.add(new Employees("Sofia Cameroon", 2016, 45000.00, "Research Analyst"));
    
     
    
    System.out.println("Sorting employees by their salary");
    
    salaryCompare salaryCompare = new salaryCompare();
    
    Collections.sort(list, salaryCompare);
    
    for (Employees Employee : list) {
    
    System.out.println(Employee.getname() + ", working as a: " + Employee.getposition() + ", since the year: "
    
    + Employee.worksince() + " Salary: " + Employee.getsalary());
    
    }
    
     
    
    System.out.println("\nSorting employees by their name");
    
    NameCompare nameCompare = new NameCompare();
    
    Collections.sort(list, nameCompare);
    
    for (Employees Employee : list) {
    
    System.out.println(Employee.getname() + ", working as a: " + Employee.getposition() + ", since the year: "
    
    + Employee.worksince() + " Salary: " + Employee.getsalary());
    
    }
    
    // Uses Comparable to sort by work experience
    
    System.out.println("\nSorting employees by their work experience");
    
    Collections.sort(list);
    
    for (Employees Employee : list) {
    
    System.out.println(Employee.getname() + ", working as a: " + Employee.getposition() + ", since the year: "
    
    + Employee.worksince() + " Salary: " + Employee.getsalary());
    
    }
    
    }
    
    }
    

    In the above example program, I created a class for Employees, with their salaries, names, position, and working since(year). The Class Employees is implementing the Comparator interface and overrides the compareTo method for integer objects and creating new classes, implementing a Comparator on them, and overriding the compare method for String and double objects. This method sorts the instances of the Student class, based on their year of working, invoked by the sort method.

    Output for the above program
    
    Sorting employees by their salary
    
    John Lewis, working as a: Business Analyst, since the year: 2020 Salary: 35000.0
    
    Atufa Shireen, working as a: Software Developer, since the year: 2019 Salary: 40000.0
    
    Dove Carson, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Sofia Cameroon, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Adam Smith, working as a: Software Developer, since the year: 2007 Salary: 60000.0
    
     
    
    Sorting employees by their name
    
    Adam Smith, working as a: Software Developer, since the year: 2007 Salary: 60000.0
    
    Atufa Shireen, working as a: Software Developer, since the year: 2019 Salary: 40000.0
    
    Dove Carson, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    John Lewis, working as a: Business Analyst, since the year: 2020 Salary: 35000.0
    
    Sofia Cameroon, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
     
    
    Sorting employees by their work experience
    
    Adam Smith, working as a: Software Developer, since the year: 2007 Salary: 60000.0
    
    Dove Carson, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Sofia Cameroon, working as a: Research Analyst, since the year: 2016 Salary: 45000.0
    
    Atufa Shireen, working as a: Software Developer, since the year: 2019 Salary: 40000.0
    
    John Lewis, working as a: Business Analyst, since the year: 2020 Salary: 35000.0
    

    This was all about comparators and comparables in java, sorting lists using them, and example programs for comparators and comparables. To get in-depth knowledge of core Java and advanced java, J2EE  SOA training along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework, and Struts through JDBC you can enroll in Certified Java Training in Chennai or Certified Java Training in Bangalore by FITA or a virtual class for this course, at an affordable price, bundled with real-time projects, certification, placement support, and career guidance assistance and an active placement cell, to make you an industry required certified java developer.

    FITA’s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.






    Quick Enquiry

    Please wait while submission in progress...


    Contact Us

    Chennai

      93450 45466

    Bangalore

     93450 45466

    Coimbatore

     95978 88270

    For Hiring

     93840 47472
     hr@fita.in

    Corporate Training

     90036 23340


    FITA Academy Branches

    Chennai
    Bangalore
    Coimbatore
    Other Locations
    FITA Academy - Velachery
    Plot No 7, 2nd floor,
    Vadivelan Nagar,
    Velachery Main Road,
    Velachery, Chennai - 600042
    Tamil Nadu

        :   93450 45466

    FITA Academy - Anna Nagar
    No 14, Block No, 338, 2nd Ave,
    Anna Nagar,
    Chennai 600 040, Tamil Nadu
    Next to Santhosh Super Market

        :   93450 45466

    FITA Academy - T Nagar
    05, 5th Floor, Challa Mall,
    T Nagar,
    Chennai 600 017, Tamil Nadu
    Opposite to Pondy Bazaar Globus

        :   93450 45466

    FITA Academy - Tambaram
    Nehru Nagar, Kadaperi,
    GST Road, West Tambaram,
    Chennai 600 045, Tamil Nadu
    Opposite to Saravana Jewellers Near MEPZ

        :   93450 45466

    FITA Academy - Thoraipakkam
    5/350, Old Mahabalipuram Road,
    Okkiyam Thoraipakkam,
    Chennai 600 097, Tamil Nadu
    Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

        :   93450 45466

    FITA Academy - Porur
    17, Trunk Rd,
    Porur
    Chennai 600116, Tamil Nadu
    Above Maharashtra Bank

        :   93450 45466

    FITA Academy Marathahalli
    No 7, J J Complex,
    ITPB Road, Aswath Nagar,
    Marathahalli Post,
    Bengaluru 560037

        :   93450 45466

    FITA Academy - Saravanampatty
    First Floor, Promenade Tower,
    171/2A, Sathy Road, Saravanampatty,
    Coimbatore - 641035
    Tamil Nadu

        :   95978 88270

    FITA Academy - Singanallur
    348/1, Kamaraj Road,
    Varadharajapuram, Singanallur,
    Coimbatore - 641015
    Tamil Nadu

        :   95978 88270

    FITA Academy - Madurai
    No.2A, Sivanandha salai,
    Arapalayam Cross Road,
    Ponnagaram Colony,
    Madurai - 625016, Tamil Nadu

        :   97900 94102

  • Trending Courses

    JAVA Training In Chennai Dot Net Training In Chennai Software Testing Training In Chennai Cloud Computing Training In Chennai AngularJS Training in Chennai Big Data Hadoop Training In Chennai Android Training In Chennai iOS Training In Chennai Web Designing Course In Chennai PHP Training In Chennai Digital Marketing Course In Chennai SEO Training In Chennai

    Oracle Training In Chennai Selenium Training In Chennai Data Science Course In Chennai RPA Training In Chennai DevOps Training In Chennai C / C++ Training In Chennai UNIX Training In Chennai Placement Training In Chennai German Classes In Chennai Python Training in Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai Core Java Training in Chennai Javascript Training in ChennaiHibernate Training in ChennaiHTML5 Training in ChennaiPhotoshop Classes in ChennaiMobile Testing Training in ChennaiQTP Training in ChennaiLoadRunner Training in ChennaiDrupal Training in ChennaiManual Testing Training in ChennaiSpring Training in ChennaiStruts Training in ChennaiWordPress Training in ChennaiSAS Training in ChennaiClinical SAS Training in ChennaiBlue Prism Training in ChennaiMachine Learning course in ChennaiMicrosoft Azure Training in ChennaiUiPath Training in ChennaiMicrosoft Dynamics CRM Training in ChennaiUI UX Design course in ChennaiSalesforce Training in ChennaiVMware Training in ChennaiR Training in ChennaiAutomation Anywhere Training in ChennaiTally course in ChennaiReactJS Training in ChennaiCCNA course in ChennaiEthical Hacking course in ChennaiGST Training in ChennaiIELTS Coaching in ChennaiSpoken English Classes in ChennaiSpanish Classes in ChennaiJapanese Classes in ChennaiTOEFL Coaching in ChennaiFrench Classes in ChennaiInformatica Training in ChennaiInformatica MDM Training in ChennaiBig Data Analytics courses in ChennaiHadoop Admin Training in ChennaiBlockchain Training in ChennaiIonic Training in ChennaiIoT Training in ChennaiXamarin Training In ChennaiNode JS Training In ChennaiContent Writing Course in ChennaiAdvanced Excel Training In ChennaiCorporate Training in ChennaiEmbedded Training In ChennaiLinux Training In ChennaiOracle DBA Training In ChennaiPEGA Training In ChennaiPrimavera Training In ChennaiTableau Training In ChennaiSpark Training In ChennaiGraphic Design Courses in ChennaiAppium Training In ChennaiSoft Skills Training In ChennaiJMeter Training In ChennaiPower BI Training In ChennaiSocial Media Marketing Courses In ChennaiTalend Training in ChennaiHR Courses in ChennaiGoogle Cloud Training in ChennaiSQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai

  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!