You can create two Comparator classes, one for comparing salary and another one for comparing names.
Then you can call the sort(Comparator) method on the list to sort it using that comparator.
Example:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("b", 5));
employeeList.add(new Employee("a", 10));
employeeList.add(new Employee("c", 1));
employeeList.sort(new NameComparator());
System.out.println("by name:");
employeeList.forEach(System.out::println);
employeeList.sort(new SalaryComparator());
System.out.println("by salary:");
employeeList.forEach(System.out::println);
}
}
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
class NameComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
}
class SalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return Integer.compare(o1.salary, o2.salary);
}
}
This generates the following output:
by name:
Employee{name='a', salary=10}
Employee{name='b', salary=5}
Employee{name='c', salary=1}
by salary:
Employee{name='c', salary=1}
Employee{name='b', salary=5}
Employee{name='a', salary=10}
Depending on the complexity of your project, you can have a static factory function to get comparators.
class EmpComparatorFactory {
public static Comparator<Employee> getComparator(EmpSort sortType) {
switch (sortType) {
case NAME_ASC:
return new EmpComparatorName();
case NAME_DSC:
return new EmpComparatorName().reversed();
case SALARY_ASC:
return new EmpComparatorSalary();
case SALARY_DSC:
return new EmpComparatorSalary().reversed();
default:
return null;
}
}
static class EmpComparatorName implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
}
static class EmpComparatorSalary implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return Integer.compare(o1.salary, o2.salary);
}
}
}
enum EmpSort {
NAME_ASC, NAME_DSC, SALARY_ASC, SALARY_DSC
}
You can then sort the list like this employeeList.sort(EmpComparatorFactory.getComparator(EmpSort.NAME_ASC));