@Data
public class Flattening {
private final List<Company> companies;
public static List<String> flatWithSpecialToStreamMethod() {
List<String> streamEmployeeNames = companies.stream()
.flatMap(Company::getDepartmentsStream)
.flatMap(Department::getEmployeesStream)
.map(Employee::getName)
.collect(toList());
return streamEmployeeNames;
}
// all getXXXStream must return appropriate stream or in case of Collection (closed source) use
public static List<String> flatWithCollections() {
List<String> streamEmployeeNames = companies.stream()
.map(Company::getDepartments).flatMap(Collection::stream)
.map(Department::getEmployees).flatMap(Collection::stream)
.map(Employee::getName)
.collect(toList());
return streamEmployeeNames;
}
}