0

我有一个 ArrayList,我想对内容进行排序,以便首先对任何带有英文字母的内容进行排序,然后对任何带有数字和非英文字符的内容进行排序。

例如: A, B , C ... Z, 1 , 2, 3 ... 9, _test1,_2, ...

目前我只知道如何按字母顺序对项目进行排序。建议?

class Comparator implements Comparator<Name> {
    @Override
    public int compare(Name name1, Name name2) {            
        return name1.getName().toLowerCase().compareTo(name2.getName().toLowerCase());
    }
}
4

1 回答 1

6

您可以使用 Comparator 的以下实现:

    Comparator<String> comparator = new Comparator<String>() {

        @Override
        public int compare(String lhs, String rhs) {
            boolean lhsStartsWithLetter = Character.isLetter(lhs.charAt(0));
            boolean rhsStartsWithLetter = Character.isLetter(rhs.charAt(0));

            if ((lhsStartsWithLetter && rhsStartsWithLetter) || (!lhsStartsWithLetter && !rhsStartsWithLetter)) {
                // they both start with letters or not-a-letters
                return lhs.compareTo(lhs);
            } else if (lhsStartsWithLetter) {
                // the first string starts with letter and the second one is not
                return -1;
            } else {
                // the second string starts with letter and the first one is not
                return 1;
            }
        }
    };
于 2013-02-26T08:19:02.007 回答