java 8 optional to replace return null

Viewed 5489

I am refactoring the code to Java 8 and I want to replace null checks with Optional.

public Employee findEmployeeById(String id) {
    List<Employee> 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()?

4 Answers
Related