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());
    }
}
1

1 Answer 1

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;
            }
        }
    };
Sign up to request clarification or add additional context in comments.

1 Comment

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.