Why don't you just replace your method:
public Optional<Employee> findEmployeeById(String id) { List<Employee> empList = ..
I suggest you wrap empList.get(0) in Optional.ofNullable if it can still be empty.
How much better is it: think of the calling method. Whoever calls, your method should think what to actually do when the result is empty .
In addition, now you force the code, for example:
Optional<Employee> emp = findEmployeeById("12"); if (emp.isPresent()) { } else { .... }
You can also link this to become more free:
emp.orElseThrow(RuntimeException::new)
Or other optional methods.
This is simply not the case when you return an Employee. You donβt even think (usually) to check if the link is null.
This makes your code less error prone and more understandable.
source share