我正在尝试使用以下命令添加两个可为空的列表:
List<Employee> employees = null;
if (<some condition>) {
employees = employeeService.getEmployees(<some criteria>);
// Add another list of employees
if (<some condition>) {
List<Employee> employeesSubList = employeeService.getEmployees(<some other criteria>));
if (!isEmpty(employeesSubList)) {
if (!isEmpty(employees)) {
employees.addAll(employeesSubList);
} else {
employees = employeesSubList;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可行,但代码看起来非常丑陋。有一个硬条件,List<Employee> employees如果没有员工存在,父级将为空而不是空列表。有没有更干净的方法来做同样的事情?
我尝试了 Java 8 方法,但 IntelliJ 抛出了一些警告.orElse(emptyList()).addAll(employeesSubList):
List<Employee> employees = null;
if (<some condition>) {
employees = employeeService.getEmployees(<some criteria>);
// Add another list of employees
if (<some condition>) {
List<Employee> employeesSubList = employeeService.getEmployees(<some other criteria>));
if (!isEmpty(employeesSubList)) {
Optional.ofNullable(employees).orElse(emptyList()).addAll(employeesSubList);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Intellij 可能告诉您的“问题”是emptyList().addAll()1)一个错误,因为这是一个不可变列表 2)从未分配给任何内容,并且它返回一个布尔值,因此您需要一种不同的方式来获取该数据
另外,您可以摆脱 if 语句,因为将空列表添加到另一个列表是无操作的
例如
// assumes employees is not null
employees.addAll(
Optional.ofNullable(employeeService.getEmployees(<some other criteria>))).orElse(emptyList())
);
Run Code Online (Sandbox Code Playgroud)