JAVA树结构数据处理

前端用的vant,以vant结构为基础,可自行修改

public class TreeVo {
    private Integer pid;
    private Integer id;
    private String text;
    private List<TreeVo> children;
    //get set方法省略了    
}
public class Tree {
    private Integer rootId = 0; //根节点配置
    private List<TreeVo> treeVoList = new ArrayList<TreeVo>();
    public Tree(List<TreeVo> treeVoList) {
        this.treeVoList = treeVoList;
    }
    //建立树形结构
    public List<TreeVo> builTree(){
        List<TreeVo> treeVoList = new ArrayList<TreeVo>();
        for(TreeVo treeVo : getRootNode()) {
            treeVo = buildChildTree(treeVo);
            treeVoList.add(treeVo);
        }
        return treeVoList;
    }

    //递归,建立子树形结构
    private TreeVo buildChildTree(TreeVo treeVo){
        List<TreeVo> childTree = new ArrayList<TreeVo>();
        for(TreeVo nodeTreeVo : treeVoList) {
            if(nodeTreeVo.getPid().equals(treeVo.getId())) {
                childTree.add(buildChildTree(nodeTreeVo));
            }
        }
        if(childTree.size() > 0){ //前端框架中,只要是[],它就有展开节点,所以做个判断去掉
            treeVo.setChildren(childTree);
        }
        return treeVo;
    }

    //获取根节点
    private List<TreeVo> getRootNode() {
        List<TreeVo> rootTreeList =new  ArrayList<TreeVo>();
        for(TreeVo treeVo : treeVoList) {
            if(treeVo.getPid() == rootId) {
                rootTreeList.add(treeVo);
            }
        }
        return rootTreeList;
    }
}

 

posted @ 2021-11-20 14:27  黑~白  阅读(351)  评论(0编辑  收藏  举报