I have taken value from my database and put it into resultset and display it in JTable,but I am facing some sorting problem which is my primary key e.g. A1,A2,A3....A10,A11.But in my JTable,that primary key column has been displayed incorrectly.
A11 A10 A1 A2 A3 A4
A11 should be at the last.Is there anyway to solve this issue??
Strings
are ordered alphabetically by default. You need to implement your own Comparator<String>
.
Try below comparator
public class CustomComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
int num1 = Integer.parseInt(str1.substring(1,str1.length()));
int num2 = Integer.parseInt(str2.substring(1, str2.length()));
return num1 - num2;
}
}
Run with your input
public static void main(String[] args) {
String[] a = {"A11","A10", "A1" ,"A2", "A3", "A4"};
Arrays.sort(a,new CustomComparator());
System.out.println(Arrays.asList(a).toString());
}
Output
[A1, A2, A3, A4, A10, A11]