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

后端 未结 8 830
既然无缘
既然无缘 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:42

    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.

提交回复
热议问题