java实现多级菜单

/**
 * 查询所有菜单
 */
public BaseWebResponse getAllMenus() {

    List systemMenuInfoList = menuInfoMapper.getAllMenus();

    List menuTree = buildMenuTree(systemMenuInfoList);
    return setResultSuccess("信息查询成功", menuTree);
}

/**
 * 构建菜单树
 */
private List buildMenuTree(List allMenus) {
    //用于存放根菜单
    List rootMenus = new ArrayList<>();
    Map> menuMap = new HashMap<>();

    // 将菜单按照父菜单ID分组,放在menuMap中
    for (SystemMenuInfo menu : allMenus) {
        int parentId = menu.getPid() != null ? menu.getPid() : 0;
        if (!menuMap.containsKey(parentId)) {
            menuMap.put(parentId, new ArrayList<>());
        }
        menuMap.get(parentId).add(menu);
    }

    // 从根菜单开始,构建菜单树
    rootMenus.addAll(menuMap.getOrDefault(0, new ArrayList<>()));
    for (SystemMenuInfo rootMenu : rootMenus) {
        buildSubMenuTree(rootMenu, menuMap);
    }

    return rootMenus;
}

/**
 * 根据父菜单节点逐级构建子树,按顺序排列
 */
private void buildSubMenuTree(SystemMenuInfo parentMenu, Map> menuMap) {
    //获取根菜单的子节点列表
    List children = menuMap.getOrDefault(parentMenu.getMenuId(), new ArrayList<>());
    Collections.sort(children);
    parentMenu.setChildren(children);
    for (SystemMenuInfo childMenu : children) {
        buildSubMenuTree(childMenu, menuMap);
    }
}

你可能感兴趣的:(java)