I try to solve to problem with tree traversing. I feel I very close to solve it but I need more clue.
So I have two interfaces:
public interface Department {
String getName();
String getType();
}
public interface Company extends Department {
List<Department> getDepartments();
}
So this creates Tree structure.
I want to find Department List by type.
I implemented finding a single element already.
public class Concern {
private List<Department> getDepartments;
public Optional<Department> findDepartmentByName(String name) {
return findDepartmentByPredicate(department -> department.getName().equals(name)).findFirst();
}
public List<Department> findDeparmentByType(String type) {
return findDepartmentByPredicate(department -> deparment.getType().equals(type))
.toList();
}
private Stream<Department> findDepartmentByPredicate(Predicate<Department> predicate) {
return department.stream()
.map(department -> department.getMatchingDepartment(predicate))
.filter(Optional::isPresent)
.map(Optional::get);
}
}
I trying using this with one function.
public interface Department {
....
default Optional<Department> getMatchingDepartment(Predicate<Department> predicate) {
if (predicate.test(this)) {
return Optional.of(this);
}
return Optional.empty();
}
}
And this is a part where I don't how to do this.
I try to call getMatchingDepartment on every list element but it don't traverse all child elements.
public interface Comapny extends Deparment {
default Optional<Department> getMatchingDepartment(Predicate<Department> predicate) {
return getDepartments().stream()
.map(department -> department.getMatchingDepartment(predicate))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
}
Is it possible to do this that way ? I need to use recursion somehow?