1

I am trying to add all the prices of given products as:

 BigDecimal getTotalPrice(List<Product> products) {
        return products.stream()
                .map(Product::getPrice)
                .peek(bigDecimal -> System.out.println(bigDecimal))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

I tried printing all the values of bigDecimal, whenever we get value as null we are getting java.lang.NullPointerException, is there any better way to addition in the java 8 by preventing any kind of Exceptions?

implosivesilence
  • 536
  • 10
  • 24
  • If you want to filter them out add `.filter(bigDecimal -> bigDecimal != null)` or `.filter(Objects::nonNull)` before `reduce` – Thiyagu Nov 19 '20 at 08:52
  • you can use filter operator before map, you can filter products.stream() .filter(x->x!=null) .map(Product::getPrice) .peek(bigDecimal -> System.out.println(bigDecimal)) .reduce(BigDecimal.ZERO, BigDecimal::add); ore you can use Optional wrapper .map(x-> Optionale.ofNullable(x.getPrice).orElse(0)) – raffaeleambrosio Nov 19 '20 at 08:52
  • Note also that you can say `peek(System.out::println)`. – chrylis -cautiouslyoptimistic- Nov 19 '20 at 09:00

1 Answers1

7

I would suggest adding intermediate filter steps:

return products.stream()
               .filter(Objects::nonNull) // If products can contain null values
               .map(Product::getPrice)
               .filter(Objects::nonNull) // If price can be null
               .peek(bigDecimal -> System.out.println(bigDecimal))
               .reduce(BigDecimal.ZERO, BigDecimal::add);
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26