Java将List对象列表转为树形结构

经常遇到 菜单、部门等对象列表,输出到前端的时候需要 转换成树状结构, 一般人都想到递归调用,个人不是很喜 欢递归,重写一个简单易懂方法针对这类小需求。

假设查询部门对象列表,部门对象为 SysOrg 如下:

@Table(name = "t_sys_org")
@Data
@EqualsAndHashCode(callSuper = true)
public class SysOrg extends BaseEntity {
          
   
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "子节点列表")
    @Transient
    private List<SysOrg> childs;

    @ApiModelProperty(value = "编号")    
    @Column(name = "ORG_CODE")
    private String orgCode;
	// 其他字段省略
}

一般 service层里面的方法如下:

// ...省略部分代码
Map<Long,SysOrg> entityMap = new HashMap<>(128);
List<SysOrg> resultList = new ArrayList<>();

// 根据条件查询符合条件的部门列表, 排过序的。
List<SysOrg> entityList =  sysOrgService.searchByExample(example);

// 将List转换成Map  当然用java8 流也可以,这里用for比较清晰。
for (SysOrg entity : entityList){
          
   
    entity.setChilds(new ArrayList<>());
    entityMap.put(entity.getId(),entity);
}

// 组装成数结构列表
for (SysOrg entity : entityList){
          
   
     SysOrg parentEntity = entityMap.get(entity.getParentId());
     // 如果查询出的列表里面该节点的没有父节点说明是顶级节点
     if (ObjectUtil.isEmpty(parentEntity)){
          
   
         // 将顶级节点加入结果集中
         resultList.add(entity);
         continue;
     }
     // 把自己加到父节点对象里面去
     parentEntity.getChilds().add(entity);
 }
 // 输出最终结果
 return resultList;

个人感觉运行效率不比递归慢多少,还没测试过。

经验分享 程序员 微信小程序 职场和发展