I need to perform an add operation on two big decimals that are wrapped optionals:
Optional ordersTotal;
Optional newOrder;
<
Note that your solution
ordersTotal=ordersTotal.flatMap(b -> Optional.of(b.add(newOrder.orElse(BigDecimal.ZERO))));
will produce an empty Optional
, if ordersTotal
is empty, even if newOrder
is not.
This could be fixed by changing it to
ordersTotal=ordersTotal
.map(b -> Optional.of(b.add(newOrder.orElse(BigDecimal.ZERO))))
.orElse(newOrder);
but I’d prefer
ordersTotal=ordersTotal
.map(b -> newOrder.map(b::add).orElse(b))
.map(Optional::of).orElse(newOrder);