0

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]

1 Answer 1

1

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(). 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.