Java8 新特性踩坑篇,java.util.NoSuchElementException: No value present

今天测试老师在测试功能的时候,发现功能提交时居然报No value present错误了。而且还是在其它周边系统上,刚开始以为不是我们系统应该跟我们没关系,直到对方开发老师找过来查日志后,才发现是我写的代码有问题,哭了,还好是测试阶段;原因是我使用了Optional调用Get方法前没有先进行isPresent()判断是否为空,所以导致整个功能报废了;

一、问题

1、事故代码

	List<InsuUserVo> list=new ArrayList<>();
    InsuUserVo userVo = list.stream().filter(insuUserVo -> "1".equals(insuUserVo.getFlag())).findFirst().get();

2、抛出异常

java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	.............

二、源码分析

1、Get方法

从源码中可以看出,当Optional为空时会抛出异常;

/**
 * If a value is present in this {@code Optional}, returns the value,
 * otherwise throws {@code NoSuchElementException}.
 *
 * @return the non-null value held by this {@code Optional}
 * @throws NoSuchElementException if there is no value present
 *
 * @see Optional#isPresent()
 */
public T get() {
    if (value == null) {
        throw new NoSuchElementException("No value present");
    }
    return value;
}

2、isPresent()方法

从源码中可以看到,该方法返回了当前对象是否为Null,所以我们可以先判断当前对象不为Null时再去取值;

/**
 * Return {@code true} if there is a value present, otherwise {@code false}.
 *
 * @return {@code true} if there is a value present, otherwise {@code false}
 */
public boolean isPresent() {
    return value != null;
}

3、orElse()方法

从源码中,我们可以看到该方法会对当前的Optional对象进行非空判断,不为空则返回当前值,为空则返回指定值,利用该方法我们也可以避免异常;

/**
 * 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;
}

value就是当前的Optional对象

三、解决方案

1、方式一

        List<InsuUserVo> list=new ArrayList<>();
        Optional<InsuUserVo> op = list.stream().filter(insuUserVo -> "1".equals(insuUserVo.getFlag())).findFirst();
        InsuUserVo insuUserVo=null;
        if (op.isPresent()){
            insuUserVo=op.get();
        }

2、方式二

        List<InsuUserVo> list=new ArrayList<>();
        Optional<InsuUserVo> op = list.stream().filter(insuUserVo -> "1".equals(insuUserVo.getFlag())).findFirst();
        InsuUserVo insuUserVo = op.orElse(null);
        if (insuUserVo!=null){
            
        }

stream()常用的几种获取Optional对象的方法如下,大家在使用的时候记得检查,先进行present检验,别踩坑;

(1)、findFirst()方法
(2)、min()方法
(3)、max()方法
(4)、findAny()方法
(4)、reduce()方法

希望这篇文章可以帮到大家

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@猪大肠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值