基于多准则的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
# 1 楼答案
那么,在
Collections.sort(list, comparator)
中使用这个比较器# 2 楼答案
您可以在比较器中编写比较方法,如下所示,并将其传递到树集。我假设客户编号是唯一的,因为set不允许重复
# 3 楼答案
Java的
Arrays.sort
和Collections.sort
都是稳定的排序算法,这意味着您可以先用一个比较器排序,然后再用另一个比较器排序,第二个比较器认为相等的值仍将由第一个比较器排序看起来您已经将两个比较器组合为一个,所以只需将其传递给the version of ^{} that takes a comparator :
用n个不同的比较器串联排序
应在功能上等同于使用这些比较器的组成进行一次排序