title: How can I compare null values using Comparator?
body: <p>I've got a few <code>Comparator</code>s -- one for <code>Date</code>s, one for decimals, one for percentages, etc.</p>
  
  <p>At first my decimal comparator looked like this:</p>
  
  <pre><code>class NumericComparator implements Comparator&lt;String&gt; {
  
    @Override
    public int compare(String s1, String s2) {
      final Double i1 = Double.parseDouble(s1);
      final Double i2 = Double.parseDouble(s2);
      return i1.compareTo(i2);
    }
  
  }
  </code></pre>
  
  <p>Life was simple. Of course, this doesn't handle the case where the strings aren't parseable. So I improved <code>compare()</code>:</p>
  
  <pre><code>class NumericComparator implements Comparator&lt;String&gt; {
  
    @Override
    public int compare(String s1, String s2) {
      final Double i1;
      final Double i2;
  
      try {
        i1 = Double.parseDouble(s1);
      } catch (NumberFormatException e) {
        try {
          i2 = Double.parseDouble(s2);
        } catch (NumberFormatException e2) {
          return 0;
        }
        return -1;
      }
      try {
        i2 = Double.parseDouble(s2);
      } catch (NumberFormatException e) {
        return 1;
      }
  
      return i1.compareTo(i2);
    }
  }
  </code></pre>
  
  <p>Life was better. Tests felt more solid. However, my code reviewer pointed out, "What about <code>null</code>s?"</p>
  
  <p>Great, so now I have to repeat the above with <code>NullPointerException</code> or prepend the method body with:</p>
  
  <pre><code>if (s1 == null) {
    if (s2 == null) {
      return 0;
    } else {
      return -1;
    }
  } else if (s2 == null) {
    return 1;
  }
  </code></pre>
  
  <p>This method is huge. The worst part is, I need to repeat this pattern with <em>three other classes</em> which compare different types of strings and could raise <em>three other exceptions</em> while parsing.</p>
  
  <p>I'm not a Java expert. Is there a cleaner, neater solution than -- <em>gasp</em> -- copying and pasting? Should I trade correctness for lack of complexity so as long as it is documented?</p>
  
  <hr>
  
  <p><strong>Update:</strong> Some have suggested that it's not the <code>Comparator</code>'s job to handle <code>null</code> values. Since the sort results are displayed to users I indeed want nulls to be sorted <em>consistently</em>.</p>