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