LoginSignup
4
1

More than 5 years have passed since last update.

Java 9 Optional::stream

Last updated at Posted at 2018-06-07

下記のようにCompanyとEmployeeクラスがあって、Companyのなかに、たくさんEmployeeがある。

Employee.java
public class Employee {
  private String id;
  private String name;
}
Company.java
public class Company {
  private List<Employee> employees = new ArrayList<>();

  public Option<Employee> getEmployeeById(String employeeId) {
    return employees.stream().filter(e -> e.id.equals(employeeId)).findFirst()
  }

  public List<Employee> getEmployeeList(List<String> employeeIds) {
  }
}

次、employeeIdsのリストでEmployeeのリストを取得したくて、getEmployeeListを実装したくて、Java8とJava9実装してみる。

Java8.java
public List<Employee> getEmployeeList(Collection<String> employeeIds) {
  return employeeIds.stream()
    .map(this::getEmployeeById)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());
}
Java9.java
public List<Employee> getEmployeeList(Collection<String> employeeIds) {
  return employeeIds.stream()
    .map(this::getEmployeeById)
    .flatMap(Optional::stream)
    .collect(toList());
}

Java 9 のOptional::streamのおかげで、getEmployeeListのコードが短くなる。

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1