Java Sorting using Comparator

Lets see how we can sort our Employee objects using different criteria like id, name, salary.

SortTest remains the main class that will perform creating and filling objects for us. This time employee class is plain old java classs that holds some data about each employee we create.

Here I have created scenarios or you can say strategies OR classes for sorting as SortById,  SortByName, SortBySalary. Each of above class implements comparator interface and overrides compare method, which takes two objects to compare and return eithre -1, 1 or 0.

Note: I have added few helper functions that really helps while coding like  print – this takes array list of objects and prints in format I want instead of class id and all that. toString –  overridden this function so I can return the class string as required

Here goes the code –

Output:

As you can see –

  • we can create multiple sort strategy for sorting
  • we can compare heterogeneous objects
4 Comments
  1. Guru
    December 31, 2012 | Reply
  2. Nagarjun
    July 9, 2012 | Reply
  3. June 25, 2010 | Reply
    • Pavan
      June 25, 2010 | Reply

Add a Comment

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