Reputation: 61
I have a List of Student with tow fields (name & number), I want to sort the List by name (Persian name) but When I sort the List with Collections.sort there is problem with some Persian Alphabet like "ک" & "گ" & "ژ" &... The result is: "ی" , "ک" , "م" But it must be: "ی" , "م" , "ک"
Here is my code:
public class Student {
private String name;
private int number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", number=" + number +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
Student temp1 = new Student();
temp1.setName("ی");
temp1.setNumber(5);
Student temp2 = new Student();
temp2.setName("م");
temp2.setNumber(4);
Student temp3 = new Student();
temp3.setName("ک");
temp3.setNumber(3);
studentList.add(temp1);
studentList.add(temp2);
studentList.add(temp3);
// before sort
System.out.println("before sort");
for(Student student : studentList){
System.out.println("Student name: " + student.getName());
}
Locale locale = new Locale("fa");
System.out.println("--------------------");
System.out.println("Language: " + locale.getDisplayLanguage());
System.out.println("--------------------");
if (studentList.size() > 0) {
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(final Student object1, final Student object2) {
return Collator.getInstance(locale).compare(object1.getName(), object2.getName());
}
} );
}
// after sort
System.out.println("after sort");
for(Student student : studentList){
System.out.println("Student name: " + student.getName());
}
}
}
Upvotes: 6
Views: 1721
Reputation: 875
With the help of G3ntle_Man answer, if you use Java 8 this can be done using stream() like this
mStringList.stream().sorted(
(string1, string2) -> Collator.getInstance(
new Locale("fa", "IR"))
.compare(string1, string2)).collect(Collectors.toList());
Upvotes: 0
Reputation: 1759
Use Collator with a new locate for "IR" :
Collator.getInstance(new Locale("fa", "IR")).compare ...
Upvotes: 2
Reputation: 666
You can use a collator, take a look at this:
Performing Locale-Independent Comparisons
Or create your own Comparator. Here the doc.
The reason you are getting those strings sorted in that way is that strings are sorted using the UTF-16 char table. So in UTF-16 those characters are:
Upvotes: 3
Reputation: 8200
If such a Locale is not available in the JDK, most likely someone has already written such a library for Java. I didn't find any libraries, but maybe you can find one when you know the language.
Upvotes: 0