maxTrialfire - 1 month ago 5

Java Question

I need to perform an add operation on two big decimals that are wrapped optionals:

`Optional<BigDecimal> ordersTotal;`

Optional<BigDecimal> newOrder;

I want to achieve ordersTotal += newOrder

It's important to note that if both values are empty the result should likewise be empty (ie not zero).

Here is what I came up with:

`ordersTotal = ordersTotal.flatMap( b -> Optional.of(b.add(newOrder.orElse(BigDecimal.ZERO))));`

but I'm wondering if there's a more elegant solution.

Answer

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.

Source (Stackoverflow)

Comments