java 在访问值之前调用“Optional#isPresent()”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47042006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:28:59  来源:igfitidea点击:

Call "Optional#isPresent()" before accessing the value

javajava-8java-streamoptional

提问by Thirukumaran

As i am getting Call "Optional#isPresent()" before accessing the value in Sonar issues for the below Code Snippet , please help me to resolve this issue.

由于我在访问以下代码片段的声纳问题中的值之前收到呼叫“Optional#isPresent()”,请帮助我解决此问题。

List <Department> deptList =new ArrayList();

List<Student> studList=new ArrayList();

Department dept= studList.stream().min(comparator.comparing(Department::getDepartmentNo)).get();

Call "Optional#isPresent()" before accessing the value.

在访问值之前调用“Optional#isPresent()”

采纳答案by Damián Rafael Lattenero

For your code working, use at least one of the safe options from Option (ha, redundancy in words allowed here)

为了让您的代码正常工作,请至少使用 Option 中的安全选项之一(ha,此处允许冗余字词)

Department dept= studList.stream().min(comparator.comparing(Department::getDepartmentNo)).orElse(null);

Where "null" should be one value for the case of the empty list, I don't know the context, that's why I put null, please, don't use null!, select a correct value

对于空列表的情况,“null”应该是一个值,我不知道上下文,这就是我放null的原因,请不要使用null!,选择正确的值

回答by Danylo Zatorsky

Optional#get()throws an exception if there is nothing inside Optional. Sonar wants you to check the optional before getting the value like in the snippet below, but I won't recommend it as the whole idea of Optionalclass is to prevent null pointer exceptions

Optional#get()如果 Optional 中没有任何内容,则抛出异常。Sonar 希望您在获取下面代码片段中的值之前检查可选项,但我不会推荐它,因为Optional类的整个想法是防止空指针异常

Optional<Department> deptOpt= studList.stream().min(comparator.comparing(Department::getDepartmentNo));

Department department = null;
if(deptOpt.isPresent())
    department = deptOpt.get();
}

A better way of doing things is the fololowing:

一个更好的做事方式是以下:

Department department = deptOpt.orElse(Department::new);

In this case, deptOpt returns a default Department object in case Optional doesn't contain any value (is empty).

在这种情况下,如果 Optional 不包含任何值(为空),则 deptOpt 将返回一个默认的 Department 对象。

Anyway - whatever approach you choose should fix your problem with Sonar.

无论如何 - 无论您选择哪种方法都可以解决声纳问题。