Thursday, March 19, 2020

Java Comparator Interface

Java Comparator Interface, Oracle Java Study Materials, Oracle Java Tutorial and Material, Oracle Java Certification

There are many situations when we often need to compare two values in our Java programs. Comparing primitive values like int, char, float, boolean, etc., is very easy and we can compare them using the comparison operators like <, >, ==, etc. But what if we want to compare objects? For example, How would you compare two Employees? For this purpose, Java provides two interfaces, which are Comparable and Comparator Interface in Java.

Comparator Interface is one of the most useful topics in Java. The Comparator interface is an example of the Java library. We will also cover how to sort a collection with Java comparator with the example along with the working of Collections.Sort().

So, let’s start learning about Comparator Interface in Java.

Java Comparator Interface


Comparator Interface in Java is used to arrange or sort the objects of user-defined classes. For example, for a list of students’ objects, the natural order may be the order of employee unique id. But in real-life applications, we may want to sort the list of students by their first name, date of birth, year of admission, or simply any other such criteria. In such conditions, there is a need for the Comparator interface.

The Comparator interface of Java is present in java.util package. This interface contains 2 methods compare(Object obj1, Object obj2) and equals(Object element).

By default, we can not compare the objects of a user-defined class. To make an object of a user-defined class comparable, the class must implement the Comparable interface.

We can use the Comparator interface in the following situations:

◉ Use to sort or arrange the list or array of objects, other than the natural order.

◉ To arrange the array or list of objects where we can not modify the source code of an object to implement a Comparable interface.

◉ Use to sort the same array or list of objects in different fields.

◉ To use the group by sorting on a list or array of objects in different fields.

◉ Now, let’s understand the various methods of Java Comparator.

Methods of Java Comparator Interface


There are two methods of the Comparator Interface in Java, namely:

Methods Description
compare(Object obj1,Object obj 2) Compares the first object with another. 
equals(Object obj)   Compares the current object with the specified object. 

Comparator.compare() Method

The compare method is used to compare two objects.

Its syntax is:

public int compare(Object obj1, Object obj2)

This method compares its two arguments in order. It returns –

◉ a negative integer if the first argument is smaller than the second argument.
◉ zero, if the first argument is equal to the second argument.
◉ a positive integer, if the first argument is larger than the second argument.

For Example:

Suppose we have a Java array or an array list of our own class that contains fields like unique id, name, age, gender, etc., and we have to sort the list in the order of name or age. For this we can follow two approaches:

Approach 1:

One obvious approach is to compose our own method sort() by writing standard calculations in it. This will require going through the entire code for various basis like id, name, etc.

Approach 2:

Using this approach we can utilize the comparator interface – Java Comparator interface sorts the objects of a user-defined class. This interface in Java is available in java.util bundle package and contains 2 functions compare (Object obj1, Object obj2) and equals (Object obj).

Code to understand Collections.sort()

package com.oraclejavacertified.comparators;
import java.util.*;
// A class to represent an employee
class Employee
{
  int id, salary;
  String name;
  // Constructor
  public Employee(int id,int salary , String name)
  {
    this.id = id;
    this.salary= salary;
    this.name = name;
  }
  // Used to print student details in main()
  public String toString()
  {
    return this.id + " " + this.name+
        " " + this.salary;
  }
}
class SortById implements Comparator<Employee>
{
  // Used for sorting in ascending order of id
  public int compare(Employee a, Employee b)
  {
    return a.id - b.id;
  }
}
class SortByName implements Comparator<Employee>
{
  // Used for sorting in ascending order of name
  public int compare(Employee a, Employee b)
  {
    return a.name.compareTo(b.name);
  }
}
class SortBySalary implements Comparator<Employee>
{
  //Used for sorting in ascending order of roll salary
  public int compare(Employee a, Employee b)
  {
    return a.salary - b.salary;
  }
}
// Driver class
public class ComparatorInterfaceDemo
{
  public static void main (String[] args)
  {
    ArrayList<Employee> list = new ArrayList<Employee>();
    list.add(new Employee(111, 150000,"Rajeev"));
    list.add(new Employee(131, 100000,"Amit"));
    list.add(new Employee(121,250000, "Minie"));
    System.out.println("Unsorted List");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortById());
    System.out.println("\nSorted by ID");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortByName());
    System.out.println("\nSorted by Name");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
    Collections.sort(list, new SortBySalary());
    System.out.println("\nSorted by Salary");
    for (int i=0; i<list.size(); i++)
      System.out.println(list.get(i));
  }
}

Output:

Unsorted List
111 Rajeev 150000
131 Amit 100000
121 Minie 250000
Sorted by ID
111 Rajeev 150000
121 Minie 250000
131 Amit 100000
Sorted by Name
131 Amit 100000
121 Minie 250000
111 Rajeev 150000
Sorted by Salary
131 Amit 100000
111 Rajeev 150000
121 Minie 250000

Rules for Java Comparator Interface


There are certain rules for using Java Comparator Interface, they are as follows –

◉ You need to implement a Comparator interface if you want to sort the elements of a collection.

◉ You will need to mention the type of the parameter as Object when you override the compare() method. Because, if you do not specify any type of object in your Comparator interface, then, by default, it assumes that you are going to sort the objects of type Object.

◉ If you want to sort the elements of a user-defined type, then you need to specify the user-defined type generically while implementing the Comparator interface. When you do not specify the user-defined type while implementing the interface, then by default, it assumes them of type Object.

Java 8 Comparator Example: nullsFirst() and nullsLast() method


Here, we sort the list of elements that also contains null.

package com.oraclejavacertified.comparators;
import java.util.*;
class Employee
{
  int id;
  String name;
  int salary;
  public Employee(int id,String name,int salary)
  {
    this.id=id;
    this.name=name;
    this.salary=salary;
  }
  public int getID()
  {
    return id;
  }
  public void setID(int id)
  {
    this.id = id;
  }
  public String getName()
  {
    return name;
  }
  public void setName(String name)
  {
    this.name = name;
  }
  public int getSalary()
  {
    return salary;
  }
  public void setSalary(int age)
  {
    this.salary = age;
  }
}
// Driver class
public class ComparatorInterfaceDemo
{
  public static void main(String args[]){
    ArrayList<Employee> list=new ArrayList<Employee>();
    list.add(new Employee(101,"Rajeev",26000));
    list.add(new Employee(106,"Anil",21000));
    list.add(new Employee(105,null,30000));
                                 Comparator<Employee>cm1=Comparator.comparing(Employee::getName,Comparator.nullsFirst(String::compareTo));
    Collections.sort(list,cm1);
    System.out.println("Considers null to be less than non-null");
    for(Employee emp: list)
    {
      System.out.println(emp.id+" "+emp.name+" "+emp.salary);
    }
    Comparator<Employee>cm2=Comparator.comparing(Employee::getName,Comparator.nullsLast(String::compareTo));
    Collections.sort(list,cm2);
    System.out.println("\nConsiders null to be greater than non-null");
    for(Employee emp: list){
      System.out.println(emp.id+" "+emp.name+" "+emp.salary);
    }
  }
}

Output:

Considers null to be less than non-null
105 null 30000
106 Anil 21000
101 Rajeev 26000
Considers null to be greater than non-null
106 Anil 21000
101 Rajeev 26000
105 null 30000

Comparator vs Comparable in Java


Comparator Comparable
The Comparator sorts the attributes of different objects. Comparable interface sorts the objects with the natural order.
A Comparator interface compares the objects of two different classes. A Comparable interface compares “this” reference of the specified object.
The Comparator is present in the java.util package. The Comparable is present in java.lang package.
Comparator does not affect the original class. Comparable affects or modifies the original class.
Comparator provides compare() and equals() methods to sort the elements. Comparable provides a compareTo() method to sort the elements.

Related Posts

0 comments:

Post a Comment