Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call "Optional#isPresent()" before accessing the value [duplicate]

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.

like image 404
Thirukumaran Avatar asked Oct 31 '17 18:10

Thirukumaran


People also ask

What does a call option means?

A call option is a contract between a buyer and a seller to purchase a certain stock at a certain price up until a defined expiration date. The buyer of a call has the right, not the obligation, to exercise the call and purchase the stocks.

Is a call option bullish or bearish?

Is Buying a Call Bullish or Bearish? Buying calls is a bullish behavior because the buyer only profits if the price of the shares rises. Conversely, selling call options is a bearish behavior, because the seller profits if the shares do not rise.

What is a call option Vs put option?

A call option gives the holder the right to buy a stock and a put option gives the holder the right to sell a stock. Think of a call option as a down payment on a future purchase.


2 Answers

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

like image 52
A Monad is a Monoid Avatar answered Oct 18 '22 03:10

A Monad is a Monoid


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.

like image 20
Danylo Zatorsky Avatar answered Oct 18 '22 03:10

Danylo Zatorsky