简体   繁体   中英

how to handle Optional Object in java streams api?

I am doing simple test.

@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);


    }

and my employee table contains data:

1   Jeff Bezos  100000
2   Bill Gates  200000
3   Mark Zuckerberg 300000

the current test runs successfully.

as you can see i have prepared two list of employees ie employees and employeeList

i did so because findById method returns Optional. how can i use the streams api so that i can get list of employees simply as

List<Employee> employeeList= ....

Just merge the two stream pipelines ie

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());

We can write the code shorter using Optional.stream (requires Java 9+):

List<Employee> employees = Stream.of(empIds)
        .flatMap(id -> employeeRepository.findById(id).stream())
        .filter(e -> e.getSalary() > 200000)
        .collect(Collectors.toList());

According to the JavaDoc Optional.stream

returns a sequential Stream containing only that value, otherwise returns an empty Stream .

Thus we can go on with the filter operation at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM