流之前的Java列表空检查,并作为可选返回
我正在从API获取对象列表流之前的Java列表空检查,并作为可选返回,java,java-8,java-stream,optional,Java,Java 8,Java Stream,Optional,我正在从API获取对象列表 public Optional<List<Employee>> getEmployeeData (String deptId){ List<Employee> employee = departmentClient.employeeData(deptId); //Based on some condition I am filtering employee list but before that I wan
public Optional<List<Employee>> getEmployeeData (String deptId){
List<Employee> employee = departmentClient.employeeData(deptId);
//Based on some condition I am filtering employee list but before that I want to check for null for list.
return Optional.ofNullable(employee).orElse(Collections.emptyList())
.stream()
.filter(Objects::nonNull)
.filter(e -> e.getType != null)
.collect(Collectors.toList());
}
但我认为,由于方法返回类型是可选的,所以这是一个错误。我如何在流之前为列表检查null并作为可选返回您返回了列表,而您的方法签名是可选的
试试这个:
return employee != null ? Optional.of(employee.stream()
.filter(Objects::nonNull)
.filter(e -> e.getType != null)
.collect(Collectors.toList())) : Optional.ofNullable(Collections.emptyList());
您的解决方案不起作用,因为可选的结果是List,您通过流管道将其收集回List 使用Java 8,您可以将所有解决方案包装在可选的内部,或者更好地利用以下优点:
Optional<List<Employee>> o = Optional
.ofNullable(employees) // employees can be null, right?
.orElse(Collections.emptyList()) // ... if so, then empty List
.stream() // Stream<Employee>
.filter(Objects::nonNull) // Stream<Employee> filtered as non-nulls
.filter(e -> e.getType() != null) // Stream<Employee> with non-null field
.collect(Collectors.collectingAndThen(
Collectors.toList(), // Collected to List<Employee>
Optional::of)); // Collected to Optional<List<Employee>>
还有一个选择:
return Optional.ofNullable(employee)
.map(list -> list.stream()
.filter(Objects::nonNull)
.filter(e -> e.getType() != null)
.collect(Collectors.toList()));
里面的lambda地图。。。仅当员工列表不为空时才执行,否则返回空可选值。在这种情况下,如果员工列表为空,则抛出与问题无关的NullPointerException错误,但出于好奇:为什么该方法设计为返回可选列表,而不是在没有员工符合要求的情况下返回空列表?Optional可方便地包装可能的空值-例如,未找到匹配项,但空集合可以更好地传达这一点,并且代码更少。鉴于employee是一个集合,并且在使用stream进行示例共享时,您不需要进一步进行空检查,因此甚至不需要使用可选的ofNullableemployee。除非您有非常特殊的要求,但您没有提出,如果没有要返回的员工数据,我建议departmentClient.employeeData永远不要返回null,而是返回一个空列表。并且,您的方法getEmployeeData不会返回可选数据,而只返回一个列表,如果没有要返回的数据,还会返回一个临时列表。
return Optional.ofNullable(employee)
.map(list -> list.stream()
.filter(Objects::nonNull)
.filter(e -> e.getType() != null)
.collect(Collectors.toList()));