有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

基于多准则的java排序列表

我想根据多个标准对列表进行排序

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

基本上,我想按以下顺序排序。优先级较高的客户应位于列表的顶部,如果两个客户的优先级相同,则应优先选择一个客户编号较低的客户

原件:

Customer Priority
1        0       
2        0
3        1
4        0
5        0

应按以下顺序进行分类:

Customer   Priority
3          1
1          0
2          0
4          0
5          0

谢谢你的帮助。 DD


共 (3) 个答案

  1. # 1 楼答案

    那么,在Collections.sort(list, comparator)中使用这个比较器

  2. # 2 楼答案

    您可以在比较器中编写比较方法,如下所示,并将其传递到树集。我假设客户编号是唯一的,因为set不允许重复

    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;
    }
    
  3. # 3 楼答案

    Java的Arrays.sortCollections.sort都是稳定的排序算法,这意味着您可以先用一个比较器排序,然后再用另一个比较器排序,第二个比较器认为相等的值仍将由第一个比较器排序

    看起来您已经将两个比较器组合为一个,所以只需将其传递给the version of ^{} that takes a comparator

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

    用n个不同的比较器串联排序

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

    应在功能上等同于使用这些比较器的组成进行一次排序

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