Sort List of Strings with Localization
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 ?
Solution 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.
Solution 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);
Solution 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());
}
});