12

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.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Thirukumaran
  • 357
  • 3
  • 5
  • 17

2 Answers2

10

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.

Danylo Zatorsky
  • 5,856
  • 2
  • 25
  • 49
8

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

developer_hatch
  • 15,898
  • 3
  • 42
  • 75