添加两个可选< BigDecimal>数字的最优雅方式是什么? [英] Whats the most elegant way to add two numbers that are Optional<BigDecimal>

查看:347
本文介绍了添加两个可选< BigDecimal>数字的最优雅方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对包含可选项的两个大数小数进行加操作:

 可选< BigDecimal> ordersTotal; 
可选< BigDecimal>新命令;

我想要达到ordersTotal + = newOrder
请注意,如果两个值都是清空结果同样应该是空的(即不是零)。



以下是我想出的结果:

  ordersTotal = ordersTotal.flatMap(b  - > Optional.of(b.add(newOrder.orElse(BigDecimal.ZERO)))); 

但我想知道是否有更优雅的解决方案。


<不知道你是否会认为它更优雅,但这里有一个选择:

 

ordersTotal = Optional.of(ordersTotal.orElse(BigDecimal.ZERO).add(newOrder.orElse(BigDecimal.ZERO)));

另一个基于

  ordersTotal = Stream.of(ordersTotal,newOrder)
。 filter(可选:: isPresent)
.map(可选:: get)
.reduce(BigDecimal :: add);

请注意,第一个版本返回 Optional.of(BigDecimal.ZERO)即使两个option都是空的,而第二个将在这种情况下返回 Optional.empty()


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

Optional<BigDecimal> ordersTotal;
Optional<BigDecimal> newOrder;

I want to achieve ordersTotal += newOrder It's important to note that if both values are empty the result should likewise be empty (ie not zero).

Here is what I came up with:

ordersTotal = ordersTotal.flatMap( b -> Optional.of(b.add(newOrder.orElse(BigDecimal.ZERO))));

but I'm wondering if there's a more elegant solution.

解决方案

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.

这篇关于添加两个可选&lt; BigDecimal&gt;数字的最优雅方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆