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

后端 未结 8 826
既然无缘
既然无缘 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.

提交回复
热议问题