Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve single object from list using java8 stream api

I have a list of Employee, and I want to retrieve only one Employee information with the specific name:

public static Employee getAllEmployeeDetails(String employeeName) {
    List<Employee> empList = getAllEmployeeDetails();
    Employee employee = empList.stream().filter(x -> x.equals(employeeName));
    return employee;
}

Please let me know how to filter the data and return a single element.

like image 452
aruntheimperfect Avatar asked Dec 11 '18 07:12

aruntheimperfect


1 Answers

This will locate the first Employee matching the given name, or null if not found:

Employee employee = empList.stream()
                           .filter(x -> x.getName().equals(employeeName))
                           .findFirst()
                           .orElse(null);
like image 128
Eran Avatar answered Oct 21 '22 16:10

Eran