Simple way to sort strings in the (case sensitive) alphabetical order

Michael picture Michael · Jun 24, 2012 · Viewed 124.6k times · Source

I need to sort list of strings in the alphabetical order:

List<String> list = new ArrayList();
list.add("development");
list.add("Development");
list.add("aa");
list.add("AA");
list.add("Aa");

A common way to do it is to use comparator:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

The problem of the CaseInsensitiveComparator that “AA” is equals to “aa”. Strings appear in the result according to the order of adding for the same values, and it is not correct:

"aa","AA","Aa","development","Development"

Answer

Stephen C picture Stephen C · Jun 24, 2012

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);