使用 java 流获取列表层次结构

Get a List hierarchy using java stream

我有一个 Manager class,其中包含两个列表:

public final class Manager extends Worker // Worker is an implementation of Employee class
{
    private final List<Employee> subordinates = new ArrayList<>();
    //private final List<Employee> allSubordinates = ?
    //...
}
    

第一个包含 Employee

的实例
public abstract class Employee extends Person
{
//...
public void setManager(Manager manager)
    {
        if(this.manager != null)
        {
            this.manager.getSubordinates().remove(this);
        }
        this.manager = manager;
        this.manager.getSubordinates().add(this);
    }
}

每个经理都是一名员工,因此有自己的经理(如果是层次结构顶部则为空)。我希望我的第二个列表包含层次结构中的所有嵌套员工以及直接下属。

如果我理解了问题,你想flatMap每个下属的下属列表

manager.getSubordinates().stream()
    .flatMap(Employee::getSubordinates)
    .collect(toList())

我想出了这个和平的代码,它似乎正在做这项工作。

private final List<Employee> subordinates = new ArrayList<>();
private final List<Employee> temp = new ArrayList<>();
private final List<Employee> allSubordinates = new ArrayList<>();

public List<Employee> getAllSubordinates()
{
    allSubordinates.clear();
    allSubordinates.addAll(subordinates);
    subordinates.stream()
        .filter(employee -> employee instanceof Manager)
        .map(employee -> ((Manager) employee).getAllSubordinates())
        .forEach(temp::addAll);
    allSubordinates.addAll(temp);
    temp.clear();
    return allSubordinates;
}