0

I need to sort an array that contains null values , The null values represent invalid data that i have set to null but cannot be simply removed from the array as they represent an invalid piece of data The null values must be kept in place i.e sort all other values except the null values The error that is thrown is a NullPointerException on the call to Arrays.sort();

     public static double getMedian(Double[] values) {
     Double[] copy = Arrays.copyOf(values, values.length);
     Arrays.sort(copy);
     double median;
     if (copy.length % 2 == 0)
        median = (copy[copy.length / 2] + copy[copy.length / 2 - 1]) / 2;
     else
        median = copy[copy.length / 2];
     return median;
}

All help and/or suggestions are greatly appreciated.

5
  • 2
    Implement your own Comparator<Double> and supply it to Arrays.sort() Commented Apr 21, 2016 at 19:20
  • Have you looked at implementing your own Comparator and passing this this to the sort method? Commented Apr 21, 2016 at 19:21
  • Hi @AndreM i have looked at the Comparator api and can only find methods such as nulls first and nulls last would i need to design my own one to leave null values in place? If so how would i go about this Commented Apr 21, 2016 at 19:24
  • Hi @DenisKokorin how would i go about implementing my own comparator that leaves null values in place? Commented Apr 21, 2016 at 19:26
  • The results of a comparator are -1, 0, +1 for less than, equal or greater than. You just test for the values of your objects and return the appropriate equality value. So if (o1 == null) { return -1; } else if (o2 == null) { return +1; }, etc. Commented Apr 21, 2016 at 19:31

1 Answer 1

1

Add a comparator and then return the appropriate sign, to indicate less than, equal or greater than. For example:

class MyComparator<Double> implements Comparator {
    // change value to -1 to inverse sort direction.
    var direction = 1;

    public int compare(Double o1, Double o2) {
        int sign = 0;
        if (o1 == null) {
           sign = -1;
        } else if (o2 == null) {
           sign = +1;
        } else {
           sign = o1.compareTo(o2);
        }       
        return sign * direction;
    }

}

Arrays.sort(copy, new MyComparator());
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.