Override List Collections Sort Method

Many times we have a list of custom objects and we need to sort these objects. In such cases we need to override the compare function for Collections.sort method. In this article we discuss how to do that.

Say we have a list of employees. Each employee has id, name, and salary. Write a function to print all the employees in ascending order of their names and also find the employee with the maximum salary.

Example:

Given list of employees: [[0 Carl 10000], [1 Andy 20000], [2 Bob 30000], [3 Drake 5000]]
Output:
All Employees (Alphabetically) : [[1 Andy 20000], [2 Bob 30000], [0 Carl 10000], [3 Drake 5000]]
Employee with highest salary: [2 Bob 30000]

Use the Collections sort method and override the compare function to sort the employee’s list as per the employee name to get the list of employees sorted with ascending order of names. And to get the employees with the highest salary, override the compare function to sort the employee’s list as per the salary in descending order and then get the first employee from the list, this employee will have the highest salary.

Complete Code:

Output:

Given list of employees: [[0 Carl 10000], [1 Andy 20000], [2 Bob 30000], [3 Drake 5000]]
[[1 Andy 20000], [2 Bob 30000], [0 Carl 10000], [3 Drake 5000]]
Employee with highest salary: [2 Bob 30000]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.