title: Avoiding a java.lang.NullPointerException being thrown while performing arithmetic operations on a collection of values using lambda expressions
body: <p>Given a list of values to sum up.</p>
  
  <pre><code>List&lt;CartItems&gt; cartItems = ...
  
  BigDecimal totalWeight = cartItems.stream().reduce(BigDecimal.ZERO, (weight, cart)
          -&gt; weight.add(cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
          .setScale(SCALE, RoundingMode.HALF_UP);
  </code></pre>
  
  <p>Here, <code>cart.getProduct().getWeight()</code> may be <code>null</code> at anytime, since it is an optional field. This will thus throw a <code>java.lang.NullPointerException</code>, if one of the items contains a <code>null</code> value in the <code>weight</code> field of type <code>java.math.BigDecmial</code>.</p>
  
  <p>What is the most concise way to avoid a <code>java.lang.NullPointerException</code> being thrown when an item in a given collection contains a <code>null</code> value other than imposing a nasty conditional check like the following?</p>
  
  <pre><code>BigDecimal totalWeight = products.stream().reduce(BigDecimal.ZERO, (weight, cart)
          -&gt; weight.add(cart.getProduct().getWeight() == null ? BigDecimal.ZERO : cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
          .setScale(SCALE, RoundingMode.HALF_UP);
  </code></pre>
  
  <p>Similarly, the following will also throw a <code>java.lang.NullPointerException</code>, since the given list contains a <code>null</code> value in it.</p>
  
  <pre><code>List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;() {{
          add(1);
          add(2);
          add(3);
          add(null);
          add(5);
      }};
  
  Integer sum = list.stream().reduce(0, Integer::sum); // Or
  //Integer sum = list.stream().reduce(0, (a, b) -&gt; a + b);
  
  System.out.println("sum : " + sum);
  </code></pre>