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

23,254

Solution 1

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

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

Solution 2

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 Optional class is to prevent null pointer exceptions

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).

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

Share:
23,254
Thirukumaran
Author by

Thirukumaran

Updated on November 01, 2020

Comments

  • Thirukumaran
    Thirukumaran over 3 years

    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.

    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.