benstpierre
benstpierre

Reputation: 33591

Sorting in GWT based on String

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.

Upvotes: 4

Views: 10595

Answers (3)

Elmer Vossen
Elmer Vossen

Reputation: 11

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.

Upvotes: 1

Tom
Tom

Reputation: 44881

This is the bad boy you want: String.CASE_INSENSITIVE_ORDER

Upvotes: 12

Jason Nichols
Jason Nichols

Reputation: 11763

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.

Upvotes: 2

Related Questions