Comparator Example in Java


Description

java.util.Comparator is an interface which is used for sorting objects in Java.
Comparator having compare(Object obj1, Object obj2) method, needs to be implemented for this sorting purpose, which compares two objects and returns an integer, depending on the comparison: 1, if obj1 is greater than obj2 ; 0, if obj1 equals to obj2; -1, if obj1 is less than obj2.
Another interface that is used for sorting objects is java.lang.Comparable. However, Comparable providing natural sort order, which can not sort the objects on different attributes, Comparator can sort the objects on different attributes. Also, the method compareTo(T o) of Comparable needs to be implemented in this case, which compares the current object (this object) with the specified object for order.

Method

public int compare(Object obj1,Object obj2):

Comparator interface Example

We need to use Comparator interface when we want to order objects on different attributes, for example, let’s suppose take Employee class we would like to order by salary or by name. In this scenario, we should implement below classes.

  1. Employee .java
  2. NameComparator.java
  3. AgeComparator.java
  4. ComparatorTest.java

**Employee.java **

package com.src.comparator;

public class Employee {
	private int empAge;
	private String ename;
	private String deptName;

	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName= deptName;
	}
	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}
	public int getEmpAge() {
		return empAge;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getEname() {
		return ename;
	} 
     @Override
    public String toString() {
        return "[name=" + this.ename+ ", age=" + this.empAge+ ", deptname="
                + this.deptName "]";
    }

}

NameComparator.java

package com.src.comparator;

import java.util.Comparator;

public class NameComparator implements Comparator {

	@Override
	public int compare(Object obj1, Object obj2) {
		String name1=((Employee)obj1).getEname();
		String name2=((Employee)obj2).getEname();
		
		String dname1=((Employee)obj1).getDeptName();
		String dname2=((Employee)obj2).getDeptName();
		if(name1.equals(name2))
		{
		    return dname1.compareTo(dname2);
		}
		else
			return name1.compareTo(name2);
	}
}

** AgeComparator.java**

package com.src.comparator;

import java.util.Comparator;

public class AgeComparator implements Comparator {

	@Override
	public int compare(Object obj1,Object obj2) {
		Integer age1=((Employee)obj1).getEmpAge();
		Integer age2=((Employee)obj2).getEmpAge();
		return age1.compareTo(age2);
	}
}

ComparatorTest.java

package com.src.comparator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class ComparatorTest {

	public static void main(String[] args) {
		Employee emp[]=new Employee[2];
		emp[0]=new Employee();
		emp[0].setEmpAge(30);
		emp[0].setEname("john");
		emp[0].setDeptName("soft ware");
		
		emp[1]=new Employee();
		emp[1].setEmpAge(20);
		emp[1].setEname("mike");
		emp[1].setDeptName("Hardware");
		
		java.util.List list=new ArrayList();
		list.add(emp[0]);
		list.add(emp[1]);
		\\ Here  going to sort the objects by using Arrays.sort () method
		Arrays.sort(emp,new AgeComparator());
		System.out.println(emp[0].getEmpAge()+" "+emp[1].getEmpAge());
         \\ Here going to sort the objects by using Arrays.sort () method
		Collections.sort(list,new NameComparator());
		System.out.println(emp[0].getEname()+"    "+emp[1].getEname());
		System.out.println(emp[0].getDeptName()+"     "+emp[1].getDeptName());
	}
}