title: Working of Comparator.nullsFirst when both are null
body: <p>I have a class with several "optional" (not <code>java.util.Optional</code>) fields. I was writing a Lambda comparator to test for equality by comparing a subset of their attributes</p>
  
  <p>I wrote</p>
  
  <pre><code>private final static Comparator&lt;MyEntity&gt; COMPARATOR_491 =  
              comparing(MyEntity::getIsin)
               .thenComparing(MyEntity::getTMarketType)
               .thenComparing(nullsFirst(comparing(MyEntity::getIsoCode)))
               .thenComparing(MyEntity::getTaxRate)
               .thenComparing(nullsFirst(comparing(MyEntity::getEndDate)));
  </code></pre>
  
  <ul>
  <li>ISIN is not null</li>
  <li>Market type is not null</li>
  <li>Is code can be null</li>
  <li>Tax rate is not null</li>
  <li>End date can be null</li>
  </ul>
  
  <p>The problem is that often I get a <code>NullPointerException</code>. This is the (barely readable) stack trace</p>
  
  <pre><code>java.lang.NullPointerException: null
      at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[?:1.8.0_51]
      at java.util.Comparator$$Lambda$40/221702765.compare(Unknown Source) ~[?:?]
      at java.util.Comparators$NullComparator.compare(Comparators.java:83) ~[?:1.8.0_51]
      at java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:217) ~[?:1.8.0_51]
      at java.util.Comparator$$Lambda$42/770739971.compare(Unknown Source) ~[?:?]
      at java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:216) ~[?:1.8.0_51]
      at java.util.Comparator$$Lambda$42/770739971.compare(Unknown Source) ~[?:?]
      at java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:216) ~[?:1.8.0_51]
      at java.util.Comparator$$Lambda$42/770739971.compare(Unknown Source) ~[?:?]
  </code></pre>
  
  <p>I found that two sample entities differ by the End date. The first entity has non-null property, the second has null</p>
  
  <p>I thought that <code>nullsFirst</code> comparer could be null safe when one or both arguments are null.</p>
  
  <p>What am I doing wrong?</p>