1

I want to sort an Array of Strings with this Method:

private String[] sortAscending(String[] arrayToSort) {
    List<String> sortedList = Arrays.asList(arrayToSort);
    Collections.sort(sortedList);

    return (String[]) sortedList.toArray();
}

This will sort this Array

["Jens", "abCd", "test", "abC", "Peter"] 

to this:

["Jens", "Peter", "abC", "abCd", "test"]

but it should be

["abC", "abCd", "Jens", "Peter", "test"]`

What am I doing wrong?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Peter
  • 1,679
  • 2
  • 31
  • 60
  • 6
    Upper case letters comes before lower case letters in ASCII table. – Rohit Jain Aug 23 '14 at 15:03
  • 2
    Why convert array to list, sort it and convert it to another array? If you want to sort array instead of `Collections.sort` you can use `Arrays.sort`. – Pshemo Aug 23 '14 at 15:25

2 Answers2

6

The natural order of Strings in Java is lexicographical, which is case sensitive. Upper case letters will come before lower case letters.

Therefore you need to sort in case insensitive order :

Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER);
Eran
  • 387,369
  • 54
  • 702
  • 768
2

You should use a Collator, which orders strings using locale-sensitive rules. The default ordering of Strings is the pure lexicographic order (i.e. chars are ordered by their numeric Unicode value).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255