what about
return Character.toLowerCase(ch1) < Character.toLowerCase(ch2);
Answer from aleph_null on Stack Overflowwhat about
return Character.toLowerCase(ch1) < Character.toLowerCase(ch2);
For English (and many other languages), you can just use Character.toLowerCase as @aleph_null proposes. This compares characters based on their (lower case) Unicode code points. For some languages, however, this will be wrong. (For instance, in German, ß — eszett — comes between 's' and 't'. However, its Unicode value is U+00DF, which would make it come after 'z'.)
The only way comparing two characters makes sense is with reference to a locale. One way to do this is to use a Collator:
/**
* Compares two characters, ignoring all but primary differences. (Case
* is a tertiary difference.)
* @return true if ch1 is alphabetically smaller than ch2; false otherwise
*/
public static boolean smallestCharacter(char ch1, char ch2, Locale locale) {
Collator collator = Collator.getInstance(locale);
collator.setStrength(Collator.PRIMARY); // Collator.SECONDARY would work
return 0 > collator.compare(Character.toString(ch1),
Character.toString(ch2)
);
}
(P.S., new String(ch1) is not the way to create a String object containing a given char value.)
java - Comparing strings by their alphabetical order - Stack Overflow
How to compare characters in two strings to sort them alphabetically? (without c string library functions)
[Intro Comp. Sci.] Sorting an ArrayList of Strings Alphabetically in Java?
Collections.sort uses the natural ordering of objects in the ArrayList, which for String objects is Lexicographically. Collections.sort( ArrayList < String > ) should work the way you want.
More on reddit.comHow to compare two strings alphabetically without using "compareTo"
Videos
String.compareTo might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
Take a look at the String.compareTo method.
s1.compareTo(s2)
From the javadocs:
The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.