开发者

Sort list on base of multiple criteria

开发者 https://www.devze.com 2023-04-13 06:57 出处:网络
I would like to sort a list on base of multiple criteria. public class CustomerComparator implements Comparator<Customer> {

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());
   开发者_JS百科     }
    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.sort and Collections.sort are 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 sort that takes a comparator:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Sorting with n different comparators in series,

public static <T> void sort(Collection<T> c, Comparator<? super T>... cmps) {
  for (Comparator<? super T> cmp : cmps) { Collections.sort(c, cmp); }
}

should be functionally equivalent to sorting once with the composition of those comparators

public static <T> void sort(Collection<T> c, Comparator<? super T>... cmps) {
  Collections.sort(c, new Comparator<T>() {
    public int compare(T a, T b) {
      for (int i = cmps.length; --i >= 0;) {
        int delta = cmps[i].compare(a, b);
        if (delta != 0) { return delta; }
      }
      return 0;
    }
  });
}


You can write your compare method in your comparator like the below and pass it on to a treeset. I assume the customer numbers are unique because set does not allow duplicates.

public int compare(Customer c1, Customer c2)
{
    int i = c1.getPriority().compareTo(c2.getPriority());
    if (i != 0) return i;

    i = c1.getNumber().compareTo(c2.getNumber());
    if (i != 0) return i;

    return -1;
}


Well, use that comparator in Collections.sort(list, comparator)

0

精彩评论

暂无评论...
验证码 换一张
取 消