Skip to content

Instantly share code, notes, and snippets.

@thmain
Created June 5, 2021 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/a7de4c338251a4d40624212244dfe0ab to your computer and use it in GitHub Desktop.
Save thmain/a7de4c338251a4d40624212244dfe0ab to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Comparator;
public class OverrideArraysSort {
static int temp = 0;
static class Employee{
int id;
String name;
int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
id = temp++;
}
@Override
public String toString() {
return "[" + id + " " + name + " " + salary +"]";
}
}
public void getEmployeesAlphabetical(Employee [] employees){
//sort the array as per employee name
Arrays.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
});
System.out.println(Arrays.toString(employees));
}
public void getEmployeeWithHighestSalary(Employee [] employees){
//sort the list as per employee name
Arrays.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o2.salary-o1.salary;
}
});
System.out.println("Employee with highest salary: " + employees[0]);
}
public static void main(String[] args) {
Employee [] employees = new Employee[4];
employees[0] = new Employee("Carl", 10000);
employees[1] = new Employee("Andy", 20000);
employees[2] = new Employee("Bob", 30000);
employees[3] = new Employee("Drake", 5000);
System.out.println("Given array of employees: " + Arrays.toString(employees));
OverrideArraysSort o = new OverrideArraysSort();
o.getEmployeesAlphabetical(employees);
o.getEmployeeWithHighestSalary(employees);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment