Java – Comparator interface with example

In this article, we will discuss Comparator interface with its methods in detail

1. Comparator interface:

  • Comparator interface is used to order objects
  • This is part of original collection framework introduced in Java 1.2 version
  • Present in java.util package
  • Fully qualified name is java.util.Comparator
  • Contains two methods namely compare() and equals()
  • Method signature:
public int compare(Object object1, Object object2);
  • We can sort according to our need, either natural ordering or reverse the natural ordering by coding our own logic for compare() method
  • This is mainly used to customize sorting order [Customized Sorting Order]
  • Based on the integer value returned by compare(object2, object2) method, elements are stored/sorted,
    1. returns negative integer, if object1 less than object2 (object1 < object2)
    2. returns positive integer, if object1 greater than object2 (object1 > object2)
    3. returns Zero (0), if object1 is equal to object2 (object1 == object2)
  • We can customize Collection classes like TreeSet & TreeMap in natural or reverse order as per business requirement

2. Example on Comparator interface:

Customer.java

  • Customer POJO with 2 member variables of Integer and String type
  • 2-arg parameterized constructor
  • Overriding toString() method
package in.bench.resources.java.collection;

public class Customer {

	// member variables
	int customerId;
	String customerName;

	// 2-arg parameterized constructor
	public Customer(int customerId, String customerName) {
		super();
		this.customerId = customerId;
		this.customerName = customerName;
	}

	// override toString() method
	@Override
	public String toString() {
		return "Customer ["
				+ "customerId=" + customerId
				+ ", customerName=" + customerName
				+ "]";
	}
}

CustomerIdComparator.java

  • This is a separate class which implements Comparator interface providing customized sorting logic
  • compare() method provides reverse order sorting logic, according to customer Id
package in.bench.resources.java.collection;

import java.util.Comparator;

public class CustomerIdComparator implements Comparator<Customer> {

	@Override
	public int compare(Customer o1, Customer o2) {
		return o2.customerId - o1.customerId;
	}
}

Main class:

  • This class uses above customer POJO and customized sorting logic class implementing comparator interface, to store objects inside TreeSet
  • TreeSet stores customer objects in descending order of customer Id
  • prints customer objects in descending order of customer Id

CustomerReverseOrder.java

package in.bench.resources.java.collection;

import java.util.TreeSet;

public class CustomerReverseOrder {

	// main() method
	public static void main(String[] args) {

		// creating TreeSet object of type String
		TreeSet<Customer> ts =
				new TreeSet<Customer>(new CustomerIdComparator());

		// adding elements to TreeSet object
		ts.add(new Customer(101, "Sundar Pichai"));
		ts.add(new Customer(107, "Satya Nadella"));
		ts.add(new Customer(103, "Shiv Nadar"));
		ts.add(new Customer(102, "Shantanu Narayen"));
		ts.add(new Customer(104, "Francisco D’Souza"));
		ts.add(new Customer(106, "Vishal Sikka"));
		ts.add(new Customer(105, "Chanda Kochhar"));

		System.out.println("Customized sorting"
				+ " on basis of CustomerId\n");

		// natural ordering of customer name
		for(Customer cust : ts){
			System.out.println(cust.customerId + "  "
					+ cust.customerName);
		}
	}
}

Output:

Customized sorting on basis of Customer Id

107  Satya Nadella
106  Vishal Sikka
105  Chanda Kochhar
104  Francisco D’Souza
103  Shiv Nadar
102  Shantanu Narayen
101  Sundar Pichai

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Comparable v/s Comparator
Java - Comparable interface