I have a list of items in Persian and I want to sort them in alphabetical order.
As I understood java does not support sorting in Persian alphabetical correctly.
My code:
List<String> items = new ArrayList<>();
items.add("آب");
items.add("بابا");
items.add("تار");
items.add("پارک");
items.add("توت");
Collections.sort(items);
When I print this list the result will be:
آب
بابا
تار
توت
پارک
But it must be like this:
آب
بابا
پارک
تار
توت
The problem is with these letters گ چ پ ژ
How can I fix it?
In the code of your question Java uses the unicode order to sort the Strings, and (I have to guess) this is not helpful for Persian.
To sort correctly, you can use the Collator
functionality provided by Java.
Collator collator = Collator.getInstance(new Locale("fa", "IR"));
collator.setStrength(Collator.PRIMARY);
Collections.sort(items, collator);
I don't know if Persian is supported, though.
This code will give expected result:
import java.util.*;
public class Main {
final static String ORDER = "ا ب پ ت ث ج چ ح خ د ذ ر ز ژ س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی";
public static void main(String[] args) {
List<String> items = new ArrayList<String>();
items.add("آب");
items.add("بابا");
items.add("تار");
items.add("پارک");
items.add("توت");
Collections.sort(items, new Comparator<String>() {
@Override
public int compare(String o2, String o1) {
return ORDER.indexOf(o2.charAt(0)) -
ORDER.indexOf(o1.charAt(0));
}
});
for (String str : items) {
System.out.println(str);
}
}
}
It sort by first letter only. To order by other letters, the compare method should be improved accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With