我正在将代码重构为 Java 8,我想用 Optional 替换 null 检查。
public Employee findEmployeeById(String id) {
List<Employee> empList = .. //some db query
return (empList.isEmpty() ? null : empList.get(0));
}
Optional.ofNullable(empList.get(0))
将无法正常工作,因为它会抛出 IndexOutofBoundException
或者我应该理想地用 Optional.empty()
替换 null 吗?
最佳答案
正如@Jesper 在评论中已经提到的,您必须检查列表是否为空,然后返回一个空的 Optional
。 .
public Optional<Employee> findEmployeeById(String id) {
List<Employee> empList = .. //some db query
return empList.isEmpty() ? Optional.empty() : Optional.of(empList.get(0));
}
安Optional
是潜在 null
的包装器允许您避免显式检查 null
的值当你使用它时。
看看 Optional documentation查看它提供的功能。
例如,您可以获得员工姓名或“未知”(如果不存在),而无需检查 null
:
Optional<Employee> emp = findEmployeeById(id);
String name = emp.map(Employee::getName).orElse("unknown");
您可以阅读 this post about Uses for Optional看看你使用 Optional
是否有意义.
关于java 8 可选替换 return null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43951727/