0

I have an ArrayList and I would like to sort the contents so that anything with English alphabets are sorted first and then anything with numbers and non English characters are sorted last.

For example: A, B , C ... Z, 1 , 2, 3 ... 9, _test1,_2, ...

Currently I only know how to sort items in alphabetical order. Suggestions?

class Comparator implements Comparator<Name> {
    @Override
    public int compare(Name name1, Name name2) {            
        return name1.getName().toLowerCase().compareTo(name2.getName().toLowerCase());
    }
}
user1737884
  • 8,137
  • 4
  • 15
  • 15
  • check out this answer [stackoverflow - multiple sorting creteria](http://stackoverflow.com/questions/3704804/how-to-sort-an-arraylist-using-multiple-sorting-criteria). the fourth answer shows an example how to do it... – faceman Feb 26 '13 at 07:43

1 Answers1

6

You can use the following implementation of 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;
            }
        }
    };
tundundun
  • 634
  • 1
  • 5
  • 12
  • 3
    there is a small mistake on return statement of first if condition. `return lhs.compareTo(lhs);` needs to be replaced with `return lhs.compareTo(rhs);` – Gökhan Barış Aker Oct 19 '15 at 12:37