I need to perform an add operation on two big decimals that are wrapped optionals:
Optional ordersTotal;
Optional newOrder;
<
Optional and Stream here do not fit together elegantly.
The best in java 8 is:
ordersTotaI = !ordersTotaI.isPresent() ? newOrder
: !newOrder.isPresent() ? ordersTotaI
: Optional.of(ordersTotaI.get().add(newOrder.get()));
However the good news is, that java 9 will add some nice (and also ugly) functionality to Optional.
Considering that you want to reassign to ordersTotal
, you'll notice that ordersTotal
only changes if newOrder
is present.
You can thus start with that check, and write it as:
if (newOrder.isPresent()) {
ordersTotal = newOrder.map(ordersTotal.orElse(ZERO)::add);
}
(This could be considered as a simplification of Stuart Marks' second solution. This is also a case where the method reference cannot be converted back to a lambda, due to ordersTotal
not being effectively final)
If you start by this check, there is also another possible “clever” approach:
if (newOrder.isPresent()) {
ordersTotal = ordersTotal.map(o -> newOrder.map(o::add)).orElse(newOrder);
}
where the intermediate map()
returns an Optional<Optional<BigDecimal>>
whose inner Optional
cannot be empty. I wouldn't consider it a good solution due to its bad readability, and I would thus recommend the first option or one of Stuart's solutions.