Java 8可选替换return null [英] java 8 optional to replace return null

查看:228
本文介绍了Java 8可选替换return null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将代码重构为Java 8,并且我想用Optional替换空检查.

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))将不起作用,因为它会抛出IndexOutofBoundException

Optional.ofNullable(empList.get(0)) won't work as when it will throw IndexOutofBoundException

或者我是否应该将Optional.empty()替换为null?

Or should I ideally replace null with Optional.empty()?

推荐答案

正如@Jesper在评论中已经提到的那样,您必须检查列表是否为空,然后返回空的Optional.

As @Jesper already mentioned in the comments, you have to check whether the list is empty and then return an empty 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时显式检查null.

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.

例如,您可以获取雇员的姓名或姓名(如果没有),而无需检查null:

For example you can get an employee's name or "unknown" if it's absent, without checking for null:

Optional<Employee> emp = findEmployeeById(id);
String name = emp.map(Employee::getName).orElse("unknown");

您可以阅读关于Uses for Optional 的信息,以了解是否适合您使用Optional.

这篇关于Java 8可选替换return null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆