I would like to sort a list on base of multiple criteria.
public class CustomerComparator implements Comparator<Customer> {
public int compare(Customer customer1, Customer customer2) {
int comparison = -1;
comparison = customer2.getCustomerPriority().compareTo(customer1.getCustomerPriority());
if( comparison == 0 ) {
comparison = customer1.getCustomerNumber().compareTo(customer2.getCustomerNumber());
}
return comparison;
}
}
Basically, I want to sort in following order. Customer with higher priority should be on top of the list, and if two customers have same priority than one with lower customer number should go first.
Original:
Customer Priority
1 0
2 0
3 1
4 0
5 0
it should be sorted as below:
Customer Priority
3 1
1 0
2 0
4 0
5 0
Thanks for help.
DD
Java’s
Arrays.sortandCollections.sortare both stable sorting algorithms meaning you can sort with one comparator and then with another, and values that are considered equivalent by the second will still be ordered by the first.It looks like you’ve already composed the two comparator’s into one though, so just pass that to the version of
sortthat takes a comparator:Sorting with n different comparators in series,
should be functionally equivalent to sorting once with the composition of those comparators