I wanted to print sorted Polish names of all available languages.
import java.util.*;
public class Tmp
{
public static void main(String... args)
{
Locale.setDefault(new Locale("pl","PL"));
Locale[] locales = Locale.getAvailableLocales();
ArrayList<String> langs = new ArrayList<String>();
for(Locale loc: locales) {
String lng = loc.getDisplayLanguage();
if(!lng.trim().equals("") && ! langs.contains(lng)){
langs.add(lng);
}
}
Collections.sort(langs);
for(String str: langs){
System.out.println(str);
}
}
}
Unfortunately I have issue with the sorting part. The output is:
:
:
kataloński
koreański
litewski
macedoński
:
:
węgierski
włoski
łotewski
Unfortunately in Polish ł
comes after l
and before m
so the output should be:
:
:
kataloński
koreański
litewski
łotewski
macedoński
:
:
węgierski
włoski
How can I accomplish that? Is there an universal non-language-dependent method (say I now want to display this and sort in another language with another sorting rules).
You can define your own
Compararable
orComparator
interface.Or also this might help you:
You should pass a Collator to the sort method:
The default sort order is defined by the Unicode codepoints in the string, and that's not the correct alphabetical order in any language.
try
it will produce
see Collator API for details
I'am dealing with the same problem. I found that the local collector solution works fine for android 7.0, but does not on earlier android versions. I've implemented the following algorithm. It is pretty fast ( I sort more than 3000 strings) and does it on earlier android versions too.
Have a look at
java.text.Collator.newInstance(Locale)
. You need to supply the Polish locale in your case. Collators implement theComparator
interface, so you can use that in sort APIs and in sorted datastructures likeTreeSet
.