There are Company and Employee classes as shown below, and there are many Employees in Company.
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) {
}
}
Next, I want to get the list of ʻEmployee in the list of ʻemployeeIds
, I want to implement getEmployeeList
, I will implement Java8 and 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's ʻOptional :: stream makes the code for
getEmployeeList` shorter.
Recommended Posts