Arjun Patel
Arjun Patel

Reputation: 81

Sort list on base of multiple criteria

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

Upvotes: 2

Views: 4980

Answers (3)

java_mouse
java_mouse

Reputation: 2109

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;
}

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120516

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;
    }
  });
}

Upvotes: 3

Bozho
Bozho

Reputation: 597106

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

Upvotes: 1

Related Questions