Avoiding a java.lang.NullPointerException being thrown while performing arithmetic operations on a collection of values using lambda expressions

Viewed 2505

Given a list of values to sum up.

List<CartItems> cartItems = ...

BigDecimal totalWeight = cartItems.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

Here, cart.getProduct().getWeight() may be null at anytime, since it is an optional field. This will thus throw a java.lang.NullPointerException, if one of the items contains a null value in the weight field of type java.math.BigDecmial.

What is the most concise way to avoid a java.lang.NullPointerException being thrown when an item in a given collection contains a null value other than imposing a nasty conditional check like the following?

BigDecimal totalWeight = products.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight() == null ? BigDecimal.ZERO : cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

Similarly, the following will also throw a java.lang.NullPointerException, since the given list contains a null value in it.

List<Integer> list = new ArrayList<Integer>() {{
        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) -> a + b);

System.out.println("sum : " + sum);
3 Answers
Related