Comparator interface in Java

For more information please go through http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave strangely. In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

The Class that implements Comparator interface must override the below method

int compare(T o1, T o2)

o1 – the first object to be compared.
o2 – the second object to be compared.

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

We will now see how we can use Comparable interface in the following example

Prerequisites

The following things are required in order to run the application

Eclipse Helios
JDK 1.6 or higher

Step 1. Create the below POJO class

Step 2. Create below class for comparing age between two employee objects

Step 3. Create below class for comparing name between two employee objects

Step 4. Create below class for comparing email between two employee objects

Step 5. Create a below test class

Step 6. Run the above class and see the below output in the console.

We can also do the same thing in different way as shown below.

Create the POJO class with below source code

Create the below test class

Run the above class and see the below output in the console

That’s all. Thank you for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.