How we can sort any class on the behalf of the properties of collection. Like we has a collection of named Employee objects we need shortlist by using Employee ID.

How we can sort any class on the behalf of the properties of collection. Like we has a collection of named Employee objects we need shortlist by using Employee ID.

We can shortlist collection objects by two ways.
1. By Implement Comparable interface.
2.By Implement Comparator interface:

1. By Implement Comparable interface.

This is used when we can change employee class. This is used only when developer has permission to implements by any interface or Comparable interface.

The steps for using the methods are :-

1. Implements the class with Comparable interface.
2. Override the compareTo(Object  obj)  method in which compare the employeeID
3. Now call Collections.sort() method and pass list as an argument.


2. By Implement Comparator interface:
This way is used when developer has no permission to implements with any interface or class is in a jar file.
1. Create a class called compactor class.
2. Implements with Comparator interface.
3. Override compare(Object obj1,Object obj2) method in which compare the employeeID .
4.Call Collection.sort() on the list and pass comparator (above class) as an argument.


Read More →