Override Arrays Sort Method – Java

Many times we have an array of custom objects and we need to sort these objects. In such cases we need to override the compare function for Arrays.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:

Input:
[[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 Arrays sort method and override the compare function to sort the employee’s array as per the employee name to get the 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 array as per the salary in descending order, and then get the first employee from the array, this employee will have the highest salary.

Complete Code:

Output:

Given array 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]