Newer
Older
huludao / src / main / java / com / newfiber / api / config / NodeTree.java
package com.newfiber.api.config;

import com.newfiber.api.pc.model.zhz.Menu;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:zzh
 * @CreateDate:2020/11/19 16:48
 * @Description:
 */
public class NodeTree {
    private List<Menu> menuList = new ArrayList<>();

    public NodeTree(List<Menu> menuList) {
        this.menuList = menuList;
    }

    /**
     * 递归构建子树型结构
     * @return
     */
    private Menu buildChilTree(Menu projectNode){
        List<Menu> childNodes = new ArrayList<>();
        for(Menu node : menuList){
            if(StringUtils.isEmpty(node.getMenuNo())){
                continue;
            }
            if(node.getParentMenuId().equals(projectNode.getMenuNo())){
                childNodes.add(buildChilTree(node));
            }
        }
        projectNode.setChildern(childNodes);
        return projectNode;
    }

    /**
     * 构建树结构
     * @return
     */
    public List<Menu> buildTree(){
        List<Menu> treeNodes = new ArrayList<>();
        for(Menu node : getRootNodes()){
            Menu projectNode = buildChilTree(node);
            treeNodes.add(projectNode);
        }
        return treeNodes;
    }

    /**
     * 获取根节点
     * @return
     */
    private List<Menu> getRootNodes(){
        List<Menu> rootTreeNodes = new ArrayList<>();
        for(Menu node :menuList){
            //如果为0  就表示为根节点
            //因为可能会有脏数据所以要判断一下 然后去除
            if(StringUtils.isEmpty(node.getMenuNo())){
                continue;
            }
            if(node.getParentMenuId().equals("0")){
                rootTreeNodes.add(node);
            }
        }
        return rootTreeNodes;
    }
}