themellion
themellion

Reputation: 41

Sort a 2-d Java String array by column while having null values

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]

Upvotes: 0

Views: 73

Answers (1)

themellion
themellion

Reputation: 41

Apologies, but it seems I was missing some extras constraints. If I add the extra constraints it seems to be working fine. So, for people who might be facing the same challenge (of sorting a string 2-d array), please see answer below:

    // Using built-in sort function Arrays.sort 
    Arrays.sort(arr, new Comparator<String[]>() {
      @Override              
      // Compare values according to columns 
      public int compare(final String[] entry1,  
                         final String[] entry2) {

          if (entry1[col] == null && entry2[col] == null) return 0;
          if (entry1[col] == null) return 1;
          if (entry2[col] == null) return -1;
          return entry1[col].compareTo(entry2[col]);
      }
    });  // End of function call sort(). 

Upvotes: 1

Related Questions