Java如何将树形Employee结构展平为带上下级关联的ConvertedEmployee列表
首先请确保Employee和ConvertedEmployee类都已生成对应的getter、setter方法,你可以通过递归+Stream Lambda的方式实现需求,一次遍历即可完成属性填充和节点展平,不需要二次处理关联关系:
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class EmployeeConverter { public List<ConvertedEmployee> flattenEmployeeTree(Employee root) { // 根节点没有上级,lead传null即可,也可根据需求传空字符串 return traverse(root, null); } private List<ConvertedEmployee> traverse(Employee currentEmployee, String leadName) { // 转换当前节点 ConvertedEmployee converted = new ConvertedEmployee(); converted.setName(currentEmployee.getName()); converted.setLead(leadName); // 用Lambda映射下属姓名列表,同时处理team为null的空指针问题 List<String> subNames = Optional.ofNullable(currentEmployee.getTeam()) .orElse(Collections.emptyList()) .stream() .map(Employee::getName) .collect(Collectors.toList()); converted.setSubordinatesNames(subNames); List<ConvertedEmployee> resultList = new ArrayList<>(); resultList.add(converted); // 递归处理所有下属节点,合并结果集 Optional.ofNullable(currentEmployee.getTeam()) .orElse(Collections.emptyList()) .stream() .map(subordinate -> traverse(subordinate, currentEmployee.getName())) .forEach(resultList::addAll); return resultList; } }
逻辑说明
- 递归遍历时主动携带当前节点的上级姓名,直接赋值给转换后节点的
lead属性,不需要遍历结束后二次关联上下级 - 当前节点的下属姓名列表直接从自身
team属性映射得到,一次遍历就能完成所有属性填充 - 用
Optional处理team为null的边界场景,避免空指针异常 - 最终返回的
resultList就是已经展平、所有节点上下级关联关系正确的List<ConvertedEmployee>结果
内容的提问来源于stack exchange,提问作者Johny Placebo
相关产品推荐
相关产品推荐

