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()));
@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
public StudentChainedComparator(Comparator
this.chainList = Arrays.asList(comparators);
}
@Override
public int compare(Student o1, Student o2) {
for( Comparator
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:
Post a Comment