title: Why does Stream.reduce(BinaryOperator) throw NullPointer when the result is null?
body: <p>I have a stream of enum values that I want to reduce. If the stream is empty or contains different values, I want <code>null</code>. If it only contains (multiple instances of) a single value, I want that value.</p>
  
  <pre><code>[]              null
  [A, B, A]       null
  [A]             A
  [A, A, A]       A
  </code></pre>
  
  <p>I tried to do it with a reduce:</p>
  
  <pre><code>return &lt;lots of filtering, mapping, and other stream stuff&gt;
         .reduce((enum1, enum2) -&gt; enum1 == enum2 ? enum1 : null)
         .orElse(null);
  </code></pre>
  
  <p>Unfortunately, this does not work, because this reduce method throws a <code>NullPointerException</code> when the result is <code>null</code>. Does anyone know why that happens? Why is <code>null</code> not a valid result?</p>
  
  <p>For now, I solved this like this:</p>
  
  <pre><code>MyEnum[] array = &lt;lots of filtering, mapping, and other stream stuff&gt;
                   .distinct()
                   .toArray(MyEnum[]::new);
  return array.length == 1 ? array[0] : null;
  </code></pre>
  
  <p>While this works, I am not satisfied with this "detour". I liked the reduce because it seemed to be the right fit and put everything into one stream.</p>
  
  <p>Can anyone think of an alternative to the reduce (that ideally is not too much code)?</p>