Chain Comparators

class StudentFirstNameComparator implements Comparator{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getFirstName().compareTo(o2.getFirstName());
    }
}




class StudentLastNameComparator implements Comparator{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getLastName().compareTo(o2.getLastName());
    }
}


public class StudentChainedComparator implements Comparator{

    List> chainList;
   
    public StudentChainedComparator(Comparator... comparators) {
        this.chainList = Arrays.asList(comparators);
    }

    @Override
    public int compare(Student o1, Student o2) {
        for( Comparator comp : chainList) {
            int result = comp.compare(o1, o2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

}
 

Test Class

Collections.sort(list,
new StudentChainedComparator(new StudentLastNameComparator(),new StudentFirstNameComparator()));

0 comments: