how to handle Optional Object in java streams api?

sagar limbu :

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 i.e 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= ....
Ousmane D. :

Just merge the two stream pipelines i.e.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113490&siteId=1