Stream之前的Java列表null检查,并作为可选返回

问题描述 投票:1回答:3

我正在从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<..>>

java java-8 java-stream optional
3个回答
0
投票

您在方法签名为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());

0
投票

您的解决方案无效,因为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
  • [功能downstreamList<Employee>映射到finisher

使用Java 9]和更高版本并使用List<Employee>,开始的地方可能会有所不同:

Optional<List<Employee>>

0
投票

还有另一种选择:

© www.soinside.com 2019 - 2024. All rights reserved.