Collator doesn't sort right for given Locale

久未见 提交于 2020-01-13 09:48:46

问题


Here's the locale alphabet order: wikipedia
Here's my code:

public static void main(String[] args) {
    Locale loc = new Locale("sr","RS");

    Collator col = Collator.getInstance(loc);
    col.setStrength(Collator.SECONDARY);

    List<String> slova = new ArrayList<String>();

    slova.add("Austrija");
    slova.add("Slovačka");
    slova.add("Č");
    slova.add("Đ");
    slova.add("C");
    slova.add("Grčka");
    slova.add("Slovenija");
    slova.add("Španija");
    slova.add("Švajcarska");
    slova.add("Švedska");
    slova.add("Srbija");

    Collections.sort(slova,col);

    for(String s: slova)
        System.out.println(s);
}

And here's the output:

Austrija
C
Č
Grčka
Slovačka
Slovenija
Španija
Srbija
Švajcarska
Švedska
Đ

As you can see from the link above this is not the correct ordering.
What am I doing wrong?


回答1:


As I found on your wikipedia page and @Vash his ISO link. I think you mean by "sr" Serbia? Then you will have to choose "cs" as country.

Edit: it depends on the java version you use. Java 6 uses the new iso standard.




回答2:


I think that the problem could be that there is no country in ISO-3166 with code RS




回答3:


If the sort order you want is not available, you can create your own order with a RuleBasedCollator. Don't be scared by the documentation of this class. It is as easy as:

String rules = "< a < b < c < ç < d ...";
RuleBasedCollator myRuleBased = new RuleBasedCollator(rules);
Collections.sort(myList, myRuleBased);



回答4:


Just found out it's a known issue caused by political and lingual circumstances. Thanks for help.



来源:https://stackoverflow.com/questions/4225523/collator-doesnt-sort-right-for-given-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!