how to sort a string alphabetically java

adrisp picture adrisp · Oct 19, 2013 · Viewed 79.2k times · Source

I want to sort a string in JAVA alphabetically, as follows Capital letter and lowercase letter followed AaBbCcDdEeFfGg. for example if I put AbaC return me AabC thanks!!

Answer

Boann picture Boann · Oct 19, 2013

You can do this using Arrays.sort, if you put the characters into an array first. (It must be an array of Character objects rather than char primitives, in order to use a custom case-insensitive comparator.)

// put the characters into an array
Character[] chars = new Character[str.length()];
for (int i = 0; i < chars.length; i++)
    chars[i] = str.charAt(i);

// sort the array
Arrays.sort(chars, new Comparator<Character>() {
    public int compare(Character c1, Character c2) {
        int cmp = Character.compare(
            Character.toLowerCase(c1.charValue()),
            Character.toLowerCase(c2.charValue())
        );
        if (cmp != 0) return cmp;
        return Character.compare(c1.charValue(), c2.charValue());
    }
});

// rebuild the string
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
str = sb.toString();