public class EmployeeJobTitleComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getJobTitle().compareTo(emp2.getJobTitle());
}
}
public class EmployeeAgeComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}
public class EmployeeSalaryComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getSalary() - emp2.getSalary();
}
}
Using a Chained Comparator
public class EmployeeChainedComparator implements Comparator {
private List> listComparators;
@SafeVarargs
public EmployeeChainedComparator(Comparator... comparators) {
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Employee emp1, Employee emp2) {
for (Comparator comparator : listComparators) {
int result = comparator.compare(emp1, emp2);
if (result != 0) {
return result;
}
}
return 0;
}
}
Using in Test Main Program
//pass the List and ChainedComparator
Collections.sort(listEmployees, new EmployeeChainedComparator(
new EmployeeJobTitleComparator(),
new EmployeeAgeComparator(),
new EmployeeSalaryComparator())
);
System.out.println("\n*** After sorting:");
for (Employee emp : listEmployees) {
System.out.println(emp);
}
Using a CompareToBuilder
import org.apache.commons.lang3.builder.CompareToBuilder;
public class EmployeeComparator implements Comparator {
@Override
public int compare(Employee o1, Employee o2) {
return new CompareToBuilder()
.append(o1.getJobTitle(), o2.getJobTitle())
.append(o1.getAge(), o2.getAge())
.append(o1.getSalary(), o2.getSalary())
.toComparison();
}
}
Switching sort order: ascending to descending
To reverse sort order from ascending to descending of a particular
attribute, simply swap the order of the two objects being compared in
the comparator. For example, the following comparator sorts the list by
job title and age in ascending order, but by salary in descending order:
public int compare(Employee o1, Employee o2) {
return new CompareToBuilder()
.append(o1.getJobTitle(), o2.getJobTitle())
.append(o1.getAge(), o2.getAge())
.append(o2.getSalary(), o1.getSalary())
.toComparison();
}
0 comments:
Post a Comment