I am refactoring the code to Java 8 and I want to replace null checks with Optional.
public Employee findEmployeeById(String id) {
List empList = .. //some db query
return (empList.isEmpty() ? null : empList.get(0));
}
Optional.ofNullable(empList.get(0)) won't work as when it will throw IndexOutofBoundException
Or should I ideally replace null with Optional.empty()?
解决方案
As @Jesper already mentioned in the comments, you have to check whether the list is empty and then return an empty Optional.
public Optional findEmployeeById(String id) {
List empList = .. //some db query
return empList.isEmpty() ? Optional.empty() : Optional.of(empList.get(0));
}
An Optional is a wrapper around a potentially null value that allows you to avoid explicitly checking for null when you use it.
Have a look at the Optional documentation to see what functionality it provides.
For example you can get an employee's name or "unknown" if it's absent, without checking for null:
Optional emp = findEmployeeById(id);
String name = emp.map(Employee::getName).orElse("unknown");
You may read this post about Uses for Optional to see if it makes sense for you to use Optional.