java 基于字符串在 GWT 中排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2149066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:42:34  来源:igfitidea点击:

Sorting in GWT based on String

javagwtsorting

提问by benstpierre

I need to sort a List based on MyDto.name in client-side GWT code. Currently I am trying to do this...

我需要在客户端 GWT 代码中根据 MyDto.name 对 List 进行排序。目前我正在尝试这样做......

Collections.sort(_myDtos, new Comparator<MyDto>() {

        @Override
        public int compare(MyDto o1, MyDto o2) {
        return o1.getName().compareTo(o2.getName());
        }
});

Unfortunately the sorting is not what I was expecting as anything in upper-case is before lower-case. For example ESP comes before aESP.

不幸的是,排序不是我所期望的,因为大写的任何内容都在小写之前。例如 ESP 出现在 aESP 之前。

回答by Tom

This is the bad boy you want: String.CASE_INSENSITIVE_ORDER

这是你想要的坏男孩:String.CASE_INSENSITIVE_ORDER

回答by Jason Nichols

That's because capital letters come before lowercase letters. It sounds like you want a case insensitive comparison as such:

那是因为大写字母在小写字母之前。听起来你想要一个不区分大小写的比较:

Collections.sort(_myDtos, new Comparator<MyDto>() {

        @Override
        public int compare(MyDto o1, MyDto o2) {
        return o1.getName().toLower().compareTo(o2.getName().toLower());
        }
});

toLower() is your friend.

toLower() 是你的朋友。

回答by Elmer Vossen

I usually go for this one:

我通常会选择这个:

@Override
public int compare(MyDto o1, MyDto o2) {
    return o1.getName().compareToIgnoreCase(o2.getName());
}

Because it seems to me that whatever String manipulations you otherwise do (toLower() or toUpper()) would turn out to be less efficient. This way, at the very least you're not creating two new Strings.

因为在我看来,无论您以其他方式执行任何字符串操作(toLower() 或 toUpper()),结果都会降低效率。这样,至少您不会创建两个新字符串。