title: Avoiding NoSuchElementException in Java 8 streams
body: <p>This question is a follow-up to an earlier question: <a href="https://stackoverflow.com/questions/22635945/adding-up-bigdecimals-using-streams#22636538">Adding up BigDecimals using Streams</a></p>
  
  <p>The question related to adding up <code>BigDecimal</code>s using Java 8 <code>Stream</code>s and Lambda expressions. After implementing the answers given, I ran into another problem: whenever the stream is empty, the <code>Optional::get()</code> method throws a <code>NoSuchElementException</code>.</p>
  
  <p>Consider the following code:</p>
  
  <pre><code>public static void main(String[] args){
      LinkedList&lt;BigDecimal&gt; values = new LinkedList&lt;&gt;();
  //        values.add(BigDecimal.valueOf(.1));
  //        values.add(BigDecimal.valueOf(1.1));
  //        values.add(BigDecimal.valueOf(2.1));
  //        values.add(BigDecimal.valueOf(.1));
  
      // Classical Java approach
      BigDecimal sum = BigDecimal.ZERO;
      for(BigDecimal value : values) {
          System.out.println(value);
          sum = sum.add(value);
      }
      System.out.println("Sum = " + sum);
  
      // Java 8 approach
      values.forEach((value) -&gt; System.out.println(value));
      System.out.println("Sum = " + values.stream().reduce((x, y) -&gt; x.add(y)).get());
  }
  </code></pre>
  
  <p>The vanilla Java code has no problem with an empty collection, but the new Java 8 code does.</p>
  
  <p>What is the most elegant way to avoid a NSEE here? Certainly we could do:</p>
  
  <pre><code>System.out.println("Sum = " + values == null || values.isEmpty() ? 0 : values.stream().reduce((x, y) -&gt; x.add(y)).get());
  </code></pre>
  
  <p>But is there a Java-8-ish way to handle empty collections?</p>