简体   繁体   中英

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.

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

You're looking for findFirst or findAny :

empList.stream()
       .filter(x -> x.getName().equals(employeeName))
.findFirst()

or

empList.stream()
       .filter(x -> x.getName().equals(employeeName))
.findAny();

However, I'd suggest changing the method return type with the use of Optional which is intended for use as a method return type where there is a need to represent "no result". in other words we let the "client" decide what to do in the "no value" case. ie

public static Optional<Employee> getAllEmployeeDetails(String employeeName) {
       return empList.stream()
           .filter(x -> x.getName().equals(employeeName))
          .findFirst()
}

you could have done .findFirst().orElse(null) but dealing with nullity is sometimes dangerous and this is a perfect opportunity to leverage the Optional<T> API.

Hi You can use multiple ways to get single object from list here i just modified the method names and also some variable names so that the code should be readable and also try to use Optional as it handles null pointer

  public static Employee findEmployeeByName(String employeeName) {
    List<Employee> empList = getAllEmployeeDetails();
    Optional<Employee> employee = empList.stream()
            .filter(employee -> employee.getName().equalsIgnoreCase(employeeName))
            .findFirst();
    return employee.isPresent() ? employee.get() : null; // Instead of null you can also return empty Employee Object
}

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