Sort List of Strings with Localization

99封情书 提交于 2019-12-17 07:23:47

问题


I want to sort below List of strings as per user locale

List<String> words = Arrays.asList(
      "Äbc", "äbc", "Àbc", "àbc", "Abc", "abc", "ABC"
    );

For different user locale sort output should be different as per there locale.

How to sort above list as per user locale ?

I tried

Collections.sort(words , String.CASE_INSENSITIVE_ORDER);

But this is not working for localization, so how to pass locale parameter to Collections.sort() or is there any other efficient way ?


回答1:


You can use a sort with a custom Comparator. See the Collator interface

Collator coll = Collator.getInstance(locale);
coll.setStrength(Collator.PRIMARY);
Collections.sort(words, coll);

The collator is a comparator and can be passed directly to the Collections.sort(...) method.




回答2:


I think this what you should be using - Collator

The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

Do something as follows in your comparator -

public int compare(String arg1, Sting arg2) {
    Collator usCollator = Collator.getInstance(Locale.US); //Your locale here
    usCollator.setStrength(Collator.PRIMARY);
    return usCollator.compare(arg1, arg2);
}

And pass an instance of the comparator the Collections.sort method.

Update

Like @Jan Dvorak said, it actually is a comparator, so you can just create it's intance with the desired locale, set the strength and pass it the sort method:

Collactor usCollator = Collator.getInstance(Locale.US); //Your locale here
usCollator.setStrength(Collator.PRIMARY); //desired strength
Collections.sort(yourList, usCollator);



回答3:


List<MODEL> ulke = new ArrayList<MODEL>();

    Collections.sort(ulke, new Comparator<MODEL>() {
        Collator collator = Collator.getInstance(new Locale("tr-TR"));
        @Override
        public int compare(MODEL o1, MODEL o2) {
            return collator.compare(o1.getULKEAD(), o2.getULKEAD());
        }
    });


来源:https://stackoverflow.com/questions/12889760/sort-list-of-strings-with-localization

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