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

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

    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);
    

提交回复
热议问题