首页 > 解决方案 > Get a List hierarchy using java stream

问题描述

I have a Manager class that contains two Lists:

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 = ?
    //...
}
    

First one contains instances of 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);
    }
}

Each Manager is an Employee, thus have their own Manager (null if it's a hierarchy top). I want my second list to contain all the nested Employees in the hierarchy in addition to direct subordinates.

标签: javajava-stream

解决方案


I came up with this peace of code, and it seems to be doing the job.

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;
}

推荐阅读