我有一个基于按字母顺序的受款人类别代码的MasterPayee对象排序,现在我需要将其他服务类别代码放在排序列表的最后
应用排序后的列表
Financial and Insurance services
Government Sectors
Other Services
Telecommunications and Utilities
Transportation Services必需列表如下所示:
Financial and Insurance services
Government Sectors
Telecommunications and Utilities
Transportation Services
Other Services需要像列表中的最后一个获得其他服务,下面的比较器用于对列表进行排序
Collections.sort(masterPayees, getCategoryNameComparatorByMasterPayee());
private Comparator<MasterPayee> getCategoryNameComparatorByMasterPayee() {
Comparator<MasterPayee> categoryNameComparatorByMasterPayee = new Comparator<MasterPayee>() {
public int compare(MasterPayee o1, MasterPayee o2) {
return (((MasterPayee) o1).getPayee_category().toString()
.compareToIgnoreCase(((MasterPayee) o2).getPayee_category().toString()));
}
};
return categoryNameComparatorByMasterPayee;
}其他服务应该总是排序列表中的最后一个
发布于 2017-02-17 12:44:04
试试这个:
Comparator<MasterPayee> categoryNameComparatorByMasterPayee = new Comparator<MasterPayee>(){
public int compare(MasterPayee o1, MasterPayee o2) {
if (((MasterPayee) o1).getPayee_category().toString().equalsIgnoreCase("Other Services") && ((MasterPayee) o1).getPayee_category().toString().equalsIgnoreCase(((MasterPayee) o2).getPayee_category().toString())) {
return 0;
}
else if (((MasterPayee) o1).getPayee_category().toString().equalsIgnoreCase("Other Services")) {
return 1;
}
else if (((MasterPayee) o2).getPayee_category().toString().equalsIgnoreCase("Other Services")) {
return -1;
}
else return (((MasterPayee) o1).getPayee_category().toString().compareToIgnoreCase(((MasterPayee) o2).getPayee_category().toString()));
}
};它将对象与“其他服务”始终视为“更大的”,从而使其出现在末尾。
发布于 2017-02-17 12:39:00
如果您知道可能排序的所有值,则可以使用番石榴‘a排序。
要创建比较器,可以如下所示:
Ordering<String> ordering1 = Ordering.explicit("Financial and Insurance services","Government Sectors","Telecommunications and Utilities","Transportation Services","Other Services");您还可以为Ordering.explicit()提供带有值的列表作为参数。
发布于 2017-02-17 12:49:49
创建一个常量映射<受款人,Integer>并在比较器中使用该值。
https://stackoverflow.com/questions/42298143
复制相似问题