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 -
Read more…