Home » Java programming language

Comparator in Java



In this article, we are going to learn about java comparator Interface. What is java Comparator? How it works?
Submitted by Jyoti Singh, on February 09, 2018

Comparator Interface

Java Comparator interface is used to compare two objects of same classes based on a criteria that is comparing by roll no. or name etc.

​We can sort the elements of an ArrayList by using the sort function but when it’s about sorting the elements based on data members, sort function is not a good choice as you will have to rewrite the sorting code for different criteria.

Using Comparator interface we can order the objects of user-defined class easily. Comparator interface is present in the java.util package Comparator class has two methods: ​

We can sort the elements of an ArrayList by using the sort function but when it’s about sorting the elements based on data members, sort function is not a good choice as you will have to rewrite the sorting code for different criteria.

Using Comparator interface we can order the objects of user-defined class easily. Comparator interface is present in the java.util package Comparator class has two methods: ​

  1. Compare (Object1, Object2) compares first object with second
  2. equals(Object element)

Here, we will be using Collection class which provides sort() method to sort the elements of the list by using the given comparator.

Syntax:

public void sort(List list , Comparator C)

Let’s see how comparator works using this short example.

Here we have five classes:

  1. Employee class (which defines the data members of class)
  2. IdComparator class implementing Comparator interface (this compares the objects using Id data member)
  3. SalaryComparator class implementing Comparator interface (this compares the objects using Salary data member)
  4. NameComparator class implementing Comparator interface (this compares the objects using Name data member)
  5. ExComparator main class<

Code

package logicProgramming;
import java.util.ArrayList;  // importing array list
import java.util.Collections; //importing collections
import java.util.Comparator; //importing Comparator

//a class to represent employee,
//this class defines all the data members for employee
class Employee
{
	public int id;
	public String name;
	public long salary;
	//Constructor
	public Employee(int id,String name,long salary)
	{ 
		this.id=id;
		this.name=name;
		this.salary=salary;
	}
}
//this class is a comparator class which will 
//compare two employee objects based on employee id  
class IdComparator implements Comparator<Employee>
{
	public int compare(Employee E1,Employee E2)
	{
		// if Id's are same that is objects are equal it will return 0
		if(E1.id==E2.id) 
			{return 0;}
		// if id of first object is greater than second object than it will return 1
		else if(E1.id>E2.id)  
			{return 1;}
		// if id of first object is less than second object than it will return -1
		else   	
			{return -1;} 		
	}
}

//This class is used to compare the employee objects by salary 
class SalaryComparator implements Comparator<Employee>
{
	public int compare(Employee E1,Employee E2)
	{
		// if salary of both object is same  it will return 0
		if(E1.salary==E2.salary) 
		{return 0;}
		// if salary  of first object is greater than second object than it will return 1
		else if(E1.salary>E2.salary) 
			{return 1;}
		// if salary of first object is less than second object than it will return -1
		else
			{return -1;} 		
	}
}	
//this class is a comparator class which will 
//compare two employee objects based on name  
//and will sort the employees alphabatically
class NameComparator implements Comparator<Employee>
{
	public int compare(Employee E1,Employee E2)
	{
		return(E1.name.compareTo(E2.name));
		
	}

}
//main class
public class ExComparator {
	public static void main(String arg[])
	{  
		ArrayList<Employee> list=new ArrayList<Employee>();//array list to hold the employee objects
		Employee E1=new Employee(100,"Muskan Singh",30885);
		Employee E2=new Employee(200,"Amitabh Singh",29000);
		Employee E3=new Employee(300,"O.P. Rai",29500);
		list.add(E1); //adding employee objects 
		list.add(E2);
		list.add(E3);
		System.out.println("\n\n\nSorting By Name............");
		Collections.sort(list, new NameComparator()); // sorting the objects of the list by name
		//looping through the list to print objects 
		for(Employee E:list)
		{
			System.out.println("Name :"+E.name+"\nId :"+E.id+"\nSalary :"+E.salary);//printing the sorted objects to the screen
			System.out.println();
		}
		System.out.println("\n\n\nSorting By Salary............");
		Collections.sort(list, new SalaryComparator()); // sorting the objects of the list by salary.

		for(Employee E:list)
		{
			System.out.println("\nSalary :"+E.salary+"\nName :"+E.name+"\nId :"+E.id);
			System.out.println();
		}
		System.out.println("\n\n\nSorting By Id............");
		Collections.sort(list, new IdComparator());// sorting the objects of the list by Id.
		//looping through the list to print objects 
		for(Employee E:list)
		{
			System.out.println("Id :"+E.id+"\nName :"+E.name+"\nSalary :"+E.salary);
			System.out.println();
		}//printing the sorted objects to the screen   
	}
}

Outout

Sorting By Name............
Name :Amitabh Singh
Id :200
Salary :29000

Name :Muskan Singh
Id :100
Salary :30885

Name :O.P. Rai
Id :300
Salary :29500




Sorting By Salary............

Salary :29000
Name :Amitabh Singh
Id :200


Salary :29500
Name :O.P. Rai
Id :300


Salary :30885
Name :Muskan Singh
Id :100




Sorting By Id............
Id :100
Name :Muskan Singh
Salary :30885

Id :200
Name :Amitabh Singh
Salary :29000

Id :300
Name :O.P. Rai
Salary :29500





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.