Whats the most elegant way to add two numbers that are Optional

后端 未结 8 833
既然无缘
既然无缘 2021-02-08 03:29

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

Optional ordersTotal;
Optional newOrder;
<         


        
相关标签:
8条回答
  • 2021-02-08 03:55

    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.

    0 讨论(0)
  • 2021-02-08 04:01

    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.

    0 讨论(0)
提交回复
热议问题