java - 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.
解决方案
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;
}
推荐阅读
- sql - 如何在 postgresql 中没有公共字段的情况下从另一个表中插入列及其值?
- esp32 - 带 LCD 的服务器 Esp32
- java - 什么样的优化JIT应用于while循环
- ios - 从 UICollectionView 中删除单元格而不重新加载
- c# - 如何为 2 个不同的变量设置计时器?
- mysql - 上传多个文件后如何得到响应?
- java - 为什么 for(T t : this) 有效,它是什么意思?
- regex - 如何在 Excel 中验证正则表达式
- camera - 有人可以告诉我在哪里可以阅读激光雷达相机交叉校准的主题
- flutter - Flutter webrtc PeerConnection 无法在 have-remote-offer 或 have-local-pranswer 之外的状态下创建答案