我正在从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 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());
}
但是我认为由于方法返回类型为Optional<>
,因此出现错误。如何在List
之前检查Stream
为空并返回为Optional<List<..>>
您在方法签名为List<Employee>
时返回了Optional<List<Employee>>
尝试这个:
return employee != null ? Optional.of(employee.stream()
.filter(Objects::nonNull)
.filter(e -> e.getType != null)
.collect(Collectors.toList())) : Optional.ofNullable(Collections.emptyList());
您的解决方案无效,因为Optional
的结果为List
,并且您通过Stream
管道将其收集回List
。
使用Java 8,您可以将所有解决方案包装在Optional
内,或者更好地利用Collectors
的优势:
Collectors
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>>
方法的行为与通常的Collector一样,提供了随后的映射功能,可获取所收集的结果。在我们的情况下,我们只需将Collectors::collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)
包装到Collectors::collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)
中即可返回。
List
收集到Optional
downstream
将List<Employee>
映射到finisher
使用Java 9]和更高版本并使用List<Employee>
,开始的地方可能会有所不同:
Optional<List<Employee>>
还有另一种选择: