Java中对象判空一行代码处理(optional方式)

问题

BigDecimal yearValue = BigDecimal.ZERO;
BigDecimal value = item.getValue();
if (value != null){
    // 使用value对象实例进行业务处理
    yearValue.add(value);
}

这里对value对象实例进行判空处理,这里需要减少此处的代码行数。

思路

使用Java中的Optional类中ofNullable方法和orElse方法来减少上述判空逻辑函数。这2个方法注解一下:

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param <T> the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

    /**
     * Return the value if present, otherwise return {@code other}.
     *
     * @param other the value to be returned if there is no value present, may
     * be null
     * @return the value, if present, otherwise {@code other}
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }
  • Optional<T> ofNullable(T value):主要是将传入的对象转化成Optional对象。如果传入的对象,为空,则返回Optional.empty(),如果对象不为空,则将传入的对象转化成Optional对象;
  • T orElse(T other):如果Optional对象中的value为空,则返回传入的other对象,如果Optional对象中的value为步空,则返回Optional对象中的value。

解决:

// 如果item.getValue()对象为空,则返回BigDecimal.ZERO;如果item.getValue()对象不为空,则返回item.getValue()对象。
BigDecimal yearValue = BigDecimal.ZERO;
yearValue.add(Optional.ofNullable(item.getValue()).orElse(BigDecimal.ZERO));

总结

以后可以使用一行Optional方式处理对象判空了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值