I am trying to sort a 2-dimensional String array in Java, using a specific column as the key to sort the array. Problem is there are null values in this column and I am getting a NullException error. Any suggestions on how to handle this kind of problem? Below is the code I have tried so far without any luck
public static void sortbyColumn(String arr[][], int col) {
Arrays.sort(arr, new Comparator<String[]>(){
@Override
public int compare(String[] first, String[] second){
if(first[2] == null) {
return 0;
}
// compare the first element
int comparedTo = first[2].compareTo(second[2]);
// if the first element is same (result is 0), compare the second element
if (comparedTo == 0) {
return first[2].compareTo(second[2]);
}
else {
return comparedTo;
}
}
});
}
Also some demo data that represents the array:
[Date, Amt, id, currency, Name, Active, Flag]
[2010-02-26, 1000000, XX1, USD, Fund1, No, 0]
[2010-02-26, 1000000, XX10, USD, Fund10, No, 0]
[2010-02-26, 1000000, XX10, USD, Fund10, No, 0]
[2010-02-26, 1000000, XX9, USD, Fund9, No, 0]
[Null, Null, Null, Null, Null, Null, Null]