1 需要确保数据排序是按照创建时间排序的,理论上父节点的创建时间比子节点要小,所以按照create time asc
父节点会在子节点前面。
package com.fhs.ucenter.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 用户下拉tree DTO
*/
@Data
public class SysUserOrgDTO {
/**
* 名字
*/
private String text;
/**
* id
*/
private String id;
/**
* 父id
*/
private String parentId;
/**
* 是否是用户
*/
private Integer isUser;
/**
* 子集合
*/
private List<SysUserOrgDTO> children = new ArrayList<>();
public SysUserOrgDTO(){}
public SysUserOrgDTO(String text, String id, String parentId, Integer isUser, List<SysUserOrgDTO> children) {
this.text = text;
this.id = id;
this.parentId = parentId;
this.isUser = isUser;
this.children = children;
}
}
上面是dto,下面是生成tree的方法 ,很简单。。比递归可读性强很多
List<SysUserOrgDTO> dbRecordList = sysUserDAO.getUserOrgTreeList(groupCode);
//找不到爸爸的才会放到此里面
List<SysUserOrgDTO> result = new ArrayList<>();
Map<String,SysUserOrgDTO> fatherDTO = dbRecordList .stream().collect(Collectors.toMap(SysUserOrgDTO::getId, item -> item));
for(SysUserOrgDTO user : dbRecord)
{
if(fatherDTO.containsKey(user.getParentId()))
{
fatherDTO.get(user.getParentId()).getChildren().add(user);
}
else{
result.add(user);
}
}
return result;