title: Java Comparator with null fields
body: <p>I have a list of entities <code>Entity</code> with the fields <code>id</code> and <code>createdDate</code>. I want to sort them as following:</p>
  
  <ul>
  <li>higher <code>id</code> first</li>
  <li>if <code>id</code> null, most recent <code>createdDate</code> first</li>
  </ul>
  
  <p>I've tried the following unsuccessfuly, as it throwns a <code>NullPointerException</code> when <code>id</code> is null</p>
  
  <pre><code>Comparator comp = Comparator
                  .nullsFirst(Comparator.comparing(e -&gt; ((Entity) e).getId()))
                  .thenComparing(e -&gt; ((Entity e).getCreatedDate())
                  .reversed();
  entities.stream().sorted(comp).findFirst();
  </code></pre>
  
  <p>For what I see, <code>Comparator.nullsFirst</code> handles when the entity is null, not when the field to be compared is null. How can I handle this situation?</p>