I need to perform an add operation on two big decimals that are wrapped optionals:
Optional ordersTotal;
Optional newOrder;
<
Not sure if you'll consider it more elegant, but here's one alternative:
ordersTotal = Optional.of(ordersTotal.orElse(BigDecimal.ZERO).add(newOrder.orElse(BigDecimal.ZERO)));
Another, based on @user140547's suggestion:
ordersTotal = Stream.of(ordersTotal, newOrder)
.filter(Optional::isPresent)
.map(Optional::get)
.reduce(BigDecimal::add);
Note that the first version returns Optional.of(BigDecimal.ZERO)
even when both optionals are empty, whereas the second will return Optional.empty()
in such a case.