Is there a way to correctly sort international strings in Android? I use a custom comparator, and a compareTo()
method, but it's not enough for me. I want letters like this "ö" to be displayed near "o", but all of them are at the end of the list. How can I force the comparator to think they are similar to "o, a, etc..."?
To locale-sensitive string comaprision use Collator
. From docs:
Performs locale-sensitive string comparison. A concrete subclass, RuleBasedCollator, allows customization of the collation ordering by the use of rule sets.
Example of comparing strings:
Collator deCollator = Collator.getInstance(Locale.GERMANY); // or new Locale("pl", "PL") for polish locale ;)
System.out.println(deCollator.compare("abcö", "abco"));
prints 1
.
If you want to sort list of strings using above collator, you can write:
final List<String> strings = Arrays.asList(
"über", "zahlen", "können", "kreativ", "Äther", "Österreich");
Collections.sort(strings, deCollator); // Collator implements Comparator
System.out.println(strings);
prints:
[Äther, können, kreativ, Österreich, über, zahlen]
EDIT: Just spotted that you are Polish, so Polish example below:
final List<String> strings = Arrays.asList(
"pięć", "piec", "Pieczka", "pięść", "pieczęć", "pieczątka");
Collections.sort(strings, Collator.getInstance(new Locale("pl", "PL")));
System.out.println(strings);
// output: [piec, pieczątka, pieczęć, Pieczka, pięć, pięść]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With