How to sort object by Comparator interface in ascending and descending order : JAVA

As in previous posts shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface and also sort user-defined classes by implements  Comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

Java : Comparable Vs Comparator

What is Comparator Interface?

java.util.Comparator  interface imposes user define sorting on different class fields  based on comparing values from different objects.  It provide compare() method which compares two objects  and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparator Interface?

Below is syntax of compare method:

public interface Comparator {
    public int compare(T o1, T o2);

}

compare() method compare two objects  fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparator interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparator  interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparable.

Note :  Below example is base on List of Employee objects it cannot be used to order a sorted collection, such as TreeSet because it generates an ordering that is not compatible with equals. It means that Comparator equates objects that the equals method does not.

In particular, any two employees who were joined on the same date will compare as equal. When you’re sorting a List this doesn’t matter; but when you’re using the Comparator to order a sorted collection, it’s fatal. If you use this Comparator to insert multiple employees joined on the same date into a TreeSet only the first one will be added to the set; the second will be seen as a duplicate element and will be ignored.

Example :

Below is simple Employee class which is having fields and getter/setter methods and also constructor to create object.

package sorting
public class Employee {
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{
}
//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}
}

Here we have created EmpComparator class and implements compare() method  of java.util.Comparator interface which will compare object fields values based on selected fields on time of sorting. ex: sortingField value.

For example : sortingField value as firstName then compare() method of  java.util.Comparator  interface will compare firstName value of passing two object on compare() method and return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;
import java.util.Comparator;

public class EmpComparator implements Comparator {
	public static final String ID = "id";
	public static final String FIRST_NAME = "firstName";
	public static final String LAST_NAME = "lastName";
	public static final String DESIGNATION = "designation";
	public static final String SALARY = "salary";
	public static final String AGE = "age";
	private String sortingField;

	@Override
	public int compare(Employee emp1, Employee emp2) {
		int diff = 0;
		switch (sortingField) {
		case ID:
			diff=emp1.getId()-emp2.getId();
			break;
		case FIRST_NAME:
			diff=emp1.getFirtsName().compareTo(emp2.getFirtsName());
			break;
		case LAST_NAME:
			diff=emp1.getLastName().compareTo(emp2.getLastName());
			break;
		case DESIGNATION:
			diff=emp1.getDesignation().compareTo(emp2.getDesignation());
			break;
		case SALARY:
			diff=(int)(emp1.getSalary()-emp2.getSalary());
			break;
		case AGE:
			diff=emp1.getAge()-emp2.getAge();
			break;

		}
		return diff;
	}

	public String getSortingField() {
		return sortingField;
	}

	public void setSortingField(String sortingField) {
		this.sortingField = sortingField;
	}
}

Here in below example creating List of Employee objects for sorting in ascending and descending order.

For sorting by firstName assigning value of sortingField as “firstName” in empComparator object. First we are using Collections.sort(List, Comparator) sorting method to sort list in ascending order by firstName because current value of sortingField is firstName. For descending order we will just reverse order of objects by Collections.resverse() method. Similarly using for lastName and also try with other fields of Employee class.

package sorting;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortComparator {

	public static void main(String[] args) {
		Employee[] empArr = {
				new Employee(1, "Saurabh", "Gupta", "Sr Project Lead", 60000, 35),
				new Employee(2, "Gaurav", "Gupta", "Developer", 50000, 32),
				new Employee(3, "Shailesh", "Nagar", "Manager", 100000, 36),
				new Employee(4, "Ankur", "Mehrotra", "Lead", 55000, 30),
				new Employee(5, "Ranjith", "Ranjan", "Tester", 35000, 45),
				new Employee(6, "Ramesh", "Bhardwaj", "Support", 25000, 35)
				};
		// Convert Array to LIst
		List empList = Arrays.asList(empArr);
		// Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		// Sort List in Ascending order by first Name
		EmpComparator empComparator = new EmpComparator();
		empComparator.setSortingField("firstName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by FirtName
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

		// Sort List in Ascending order by lastName

		empComparator.setSortingField("lastName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by last Name
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList) {
		for (Employee emp : empList) {
			System.out.println(emp);<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
		}
	}
}

Output :

********Print Employee List Before Sort********
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]

********Print Employee List in Ascending Order********
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]

********Print Employee List in Descending Order********
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]

********Print Employee List in Ascending Order********
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]

********Print Employee List in Descending Order********
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Advertisements

3 thoughts on “How to sort object by Comparator interface in ascending and descending order : JAVA”

This site uses Akismet to reduce spam. Learn how your comment data is processed.