lomza
lomza

Reputation: 9716

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

Upvotes: 7

Views: 2753

Answers (2)

user3807153
user3807153

Reputation: 1

A collator should also have a strength set beside the decomposition strategy:

final Collator collator = Collator.getInstance();
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
collator.setStrength(Collator.SECONDARY);

Collator.CANONICAL_DECOMPOSITION and a Collator.SECONDARY strength are required to sort accents/ umlauts; a full decomposition can be helpful if you want to sort unicode based characters; but this slows down sorting and requires more memory.

Upvotes: 0

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

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ęść]

Upvotes: 17

Related Questions