JAVA中 List转Tree 递归返回树形结构

1.准备List转Tree的工具类 TreeDotUtils

public class TreeDotUtils {

    /**
     * 将List转换为Tree
     * @param tList
     * @return
     */
    public static  List> convertListToTreeDot(List tList){
        List> treeDotList = new ArrayList<>();
        if(tList != null && tList.size() > 0){
            for(T t:tList){
                if(!isTreeDotExist(tList,t.getParentId())){
                    //不存在以父ID为ID的点,说明是当前点是顶级节点
                    TreeDot tTreeDot = getTreeDotByT(t, tList);
                    treeDotList.add(tTreeDot);
                }
            }
        }
        return treeDotList;
    }

    /**
     * 根据ID判断该点是否存在
     * @param tList
     * @param id
     * @param 
     * @return
     */
    private static  Boolean isTreeDotExist(List tList, String id) {
        for(T t:tList){
            if(t.getId().equals(id)){
                return true;
            }
        }
        return false;
    }

    /**
     * 根据实体获取TreeDot
     * @param t
     * @param tList
     * @param 
     * @return
     */
    private static  TreeDot getTreeDotByT(T t,List tList){
        TreeDot tTreeDot = new TreeDot<>();
        tTreeDot.setId(t.getId());
        tTreeDot.setParentId(t.getParentId());
        tTreeDot.setPermissionName(t.getPermissionName());
        tTreeDot.setParentIds(t.getParentIds());
        tTreeDot.setChildren(getChildTreeDotList(tTreeDot,tList));
        return tTreeDot;
    }

    /**
     * 获取指定父点的子树
     * @param parentTreeDot
     * @param tList
     * @param 
     * @return
     */
    private static  List> getChildTreeDotList(TreeDot parentTreeDot, List tList){
        List> childTreeDotList = new ArrayList<>();
        for(T t:tList){
            if(parentTreeDot.getId().equals(t.getParentId())){
                //如果父ID是传递树点的ID,那么就是传递树点的子点
                TreeDot tTreeDot = getTreeDotByT(t,tList);
                childTreeDotList.add(tTreeDot);
            }
        }
        return childTreeDotList;
    }
}

2.第二步 准备泛型类 TreeDot

@Data
public class TreeDot implements Serializable {


    /**
     * 点ID
     */
    private String id;
    /**
     * 点名称
     */
    private String permissionName;
    /**
     * 父点ID
     */
    private String parentId;
    /**
     * ids
     */
    private String parentIds;
    /**
     * 该点的子树集合
     */
    private List> children = new ArrayList<>();
}

3.第三步 返回对象DTO继承 TreeDot

public class PermissionTreeDTO extends TreeDot

4.查询出要进行递归的集合

List permissions = permissionMapper.selectList(queryWrapper);

5.调用TreeDotUtils.convertListToTreeDot()方法对集合进行递归 返回一个树形结构

List> treeDots = TreeDotUtils.convertListToTreeDot(permissions);

展开看效果:
JAVA中 List转Tree 递归返回树形结构_第1张图片

你可能感兴趣的:(java,list,递归算法)