Search⌘ K
AI Features

Solution: The Employee Sorter

Explore how to create a type-safe generic sorter in Java that uses Comparator to sort Employee objects by salary in descending order. Understand defining generic methods, leveraging type inference, and applying custom sorting strategies within collections.

We'll cover the following...
Java 25
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class EmployeeSorter {
static class Employee {
String name;
int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() { return name + " ($" + salary + ")"; }
}
// A specific Comparator for the Employee type
public static class SalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
// Descending order: compare e2 to e1
return Integer.compare(e2.salary, e1.salary);
}
}
// A reusable generic method that can sort ANY list using ANY comparator
public static <T> void sortItems(List<T> list, Comparator<T> sorter) {
list.sort(sorter);
}
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>();
staff.add(new Employee("Alice", 60000));
staff.add(new Employee("Bob", 45000));
staff.add(new Employee("Charlie", 90000));
SalaryComparator salarySorter = new SalaryComparator();
// The generic method infers <Employee> from the arguments
sortItems(staff, salarySorter);
System.out.println(staff);
}
}
...