Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting arraylist in alphabetical order(Persian)

Tags:

java

list

sorting

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?

like image 819
hosseinAmini Avatar asked Apr 19 '17 13:04

hosseinAmini


2 Answers

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.

like image 142
C-Otto Avatar answered Nov 03 '22 19:11

C-Otto


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.

like image 41
Sergey Krasnikov Avatar answered Nov 03 '22 19:11

Sergey Krasnikov