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

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

    I know this is an old thread, but how about this?

    orderTotal = !newOrder.isPresent()? 
                 orderTotal : 
                 newOrder.flatMap(v -> Optional.of(v.add(orderTotal.orElse(BigDecimal.ZERO));
    

    My thinking behind this approach is like this:

    • Behind all the shinny Optional etc. the basic logic here is still
      orderTotal += newOrder

    • Before the first newOrder exists orderTotal does not exist, which is represented by an empty Optional in the code.

    • If a newOrder does not exist yet (another empty Optional), no operation is necessary at all, i.e. there is no need to modify orderTotal
    • If there is a newOrder, invoke its flatMap(..) as presented in maxTrialfire's original post.

提交回复
热议问题