首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用java比较器但具有固定值的对象排序应该在排序列表中的最后一个值中。

使用java比较器但具有固定值的对象排序应该在排序列表中的最后一个值中。
EN

Stack Overflow用户
提问于 2017-02-17 12:35:53
回答 7查看 2.5K关注 0票数 4

我有一个基于按字母顺序的受款人类别代码的MasterPayee对象排序,现在我需要将其他服务类别代码放在排序列表的最后

应用排序后的列表

代码语言:javascript
复制
Financial and Insurance services

Government Sectors

Other Services

Telecommunications and Utilities

Transportation Services

必需列表如下所示:

代码语言:javascript
复制
Financial and Insurance services
Government Sectors
Telecommunications and Utilities
Transportation Services
Other Services

需要像列表中的最后一个获得其他服务,下面的比较器用于对列表进行排序

代码语言:javascript
复制
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;
}

其他服务应该总是排序列表中的最后一个

EN

Stack Overflow用户

发布于 2017-02-17 12:44:04

试试这个:

代码语言:javascript
复制
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()));
    }
};

它将对象与“其他服务”始终视为“更大的”,从而使其出现在末尾。

票数 4
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42298143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档