title: null-safe mapping Comparator using default implementations
body: <p>Is there a build-in possibility to create a null-safe mapping comparator in Java 8 without writing a own implementation of <code>Comparator</code>?</p>
  
  <p>When running the following code, it causes a NPE because the <code>keyExtractor</code> argument of <code>Comparator.comparing()</code> may return a <code>null</code> value:</p>
  
  <pre><code>public class ToSort
  {
  
      private String sortBy;
  
      public ToSort(String sortBy)
      {
          this.sortBy = sortBy;
      }
  
      public String getSortBy()
      {
          return sortBy;
      }
  
      public static void main(String[] args)
      {
          // mapping comparator
          Comparator&lt;ToSort&gt; comp = Comparator.comparing(ToSort::getSortBy);                          
          SortedSet&lt;ToSort&gt; set = new TreeSet&lt;&gt;(comp);
          ToSort o1 = new ToSort("1");
          ToSort o2 = new ToSort(null);
  
          set.add(o1);
  
          System.out.println(set.contains(o2)); //NPE because o2.getSortBy() == null
  
      }
  }
  </code></pre>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.NullPointerException
        at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
        at java.util.Comparator$$Lambda$2/1480010240.compare(Unknown Source)
        at java.util.Comparators$NullComparator.compare(Comparators.java:83)
        at java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376)
        at java.util.TreeMap.getEntry(TreeMap.java:345)
        at java.util.TreeMap.containsKey(TreeMap.java:232)
        at java.util.TreeSet.contains(TreeSet.java:234)
        at test.ToSort.main(ToSort.java:48)</p>
  </blockquote>
  
  <p>Using </p>
  
  <pre><code>Comparator&lt;ToSort&gt; comp = Comparator.nullsFirst(Comparator.comparing(ToSort::getSortBy));
  </code></pre>
  
  <p>does not work either as only <code>ToSort</code> objects that are <code>null</code> are treaded properly.</p>
  
  <p>I know how to write my own <code>Comparator</code> implementation, I`m just searching a more "elegant" solution like</p>
  
  <pre><code>Comparator.comparingNullsFirst(ToSort::getSortBy)
  </code></pre>