Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android compare special letters

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..."?

like image 624
lomza Avatar asked Feb 21 '12 12:02

lomza


1 Answers

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ęść]
like image 184
Xaerxess Avatar answered Oct 05 '22 19:10

Xaerxess