开发者

Sorting in GWT based on String

开发者 https://www.devze.com 2022-12-18 02:26 出处:网络
I need to sort a List based on MyDto.name in client-side GWT code.Currently I am trying to do this...

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

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.


This is the bad boy you want: String.CASE_INSENSITIVE_ORDER


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号