今天测试老师在测试功能的时候,发现功能提交时居然报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()方法
希望这篇文章可以帮到大家