[英]how to handle Optional Object in java streams api?
我正在做簡單的測試。
@Test
public void whenFilterEmployees_thenGetFilteredEmployees(){
Integer[] empIds = {1,2,3};
List<Optional<Employee>> employees = Stream.of(empIds)
.map(employeeRepository::findById)
.collect(Collectors.toList());
List<Employee> employeeList = employees
.stream().filter(Optional::isPresent)
.map(Optional::get)
.filter(e->e !=null)
.filter(e->e.getSalary()>200000)
.collect(Collectors.toList());
assertEquals(Arrays.asList(arrayOfEmps[2]), employeeList);
}
我的員工表包含數據:
1 Jeff Bezos 100000
2 Bill Gates 200000
3 Mark Zuckerberg 300000
當前測試成功運行。
正如您所看到的,我准備了兩個員工列表,即員工和employeeList
我這樣做是因為findById
方法返回Optional。 我如何使用流api,以便我可以簡單地獲得員工列表
List<Employee> employeeList= ....
只需合並兩個流管道即
List<Employee> employees = Stream.of(empIds)
.map(employeeRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
//.filter(e->e !=null) not needed as it's redundant
.filter(e->e.getSalary()>200000)
.collect(Collectors.toList());
我們可以使用Optional.stream
編寫更短的代碼(需要Java 9+):
List<Employee> employees = Stream.of(empIds)
.flatMap(id -> employeeRepository.findById(id).stream())
.filter(e -> e.getSalary() > 200000)
.collect(Collectors.toList());
根據JavaDoc Optional.stream
返回僅包含該值的順序
Stream
,否則返回一個空Stream
。
因此,我們可以立即繼續進行filter
操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.