Comparator in java

In this post, we will see how you can use comparator to sort list of objects in java.

Comparator:

When you want to sort the list of objects of a class,you can use Comparator interface. You don’t need to implement Comparator on the class whose objects need to be sorted. You can create a separate class and implement a Comparator interface as below.

For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

packagecom.arpit.java2blog;

import java.util.Comparator;

publicclassEmployeeSortByIdComparatorimplementsComparator{

@Override

publicintcompare(Employee e1,Employee e2){

returne1.getEmpId()-e2.getEmpId();

}

}

You can use different sorting logic based on different attributes of object that needs to be sorted.

For example:
Let’s say you want to sort list of employees by name,you can use below ocde to do that.

Anonymous Comparator:

One of advantage of Comparator over comparable is you can create anonymous comparator i.e you don’t need to implement Comparable interface to class whose objects need to be sorted.
Let’s understand more with help of example:
We will use an anonymous class to sort the list of Employees by name.