Java 之无限极分类

一、代码

package utils;

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

import entity.Auth;

public class MenuUtil {
    private static List<Auth> tree = new ArrayList<Auth>();
    /**
     * 获取导航菜单
     * @param data
     * @return
     */
    public static List<Auth> getMenu(List<Auth> data) {
        // 获取*菜单
        ArrayList<Auth> rootNode = new ArrayList<Auth>();
        for (Auth auth : data) {
            if (auth.getParent_id() == 0) {
                rootNode.add(auth);
            }
        }
        //System.out.println("rootNode = "+rootNode);
        // 获取子级菜单
        for (Auth auth : rootNode) {
            List<Auth> child = getChild(auth.getId(), data);
            auth.setChildren(child);
        }
        return rootNode;
    }

    private static List<Auth> getChild(int id, List<Auth> data) {
        //存放子菜单的集合
        ArrayList<Auth> childNode = new ArrayList<Auth>();
        for (Auth auth : data) {
            System.out.println(id == auth.getParent_id());
            if(id == auth.getParent_id()) {
                childNode.add(auth);
            }
        }
        //递归子级
        for (Auth auth : childNode) {
            auth.setChildren(getChild(auth.getId(), data));
        }
        if(childNode.size() == 0) {
            return null;
        }
        return childNode;
    }
    
    /**
     * 获取无限极分类
     * @param data
     * @param parent_id
     * @param level
     * @return
     */
    public static List<Auth> getAuthList(List<Auth> data, int parent_id, int level) {
        for(Auth auth : data) {
            if(auth.getParent_id() == parent_id) {
                auth.setLevel(level);
                tree.add(auth);
                getAuthList(data, auth.getId(), level + 1);
            }
        }
        return tree;
    }
}

 

上一篇:Postman请求Https接口与认证


下一篇:CactiEZ web登录密码忘记;重置密码