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.
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 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With