shikeyin
2024-01-11 65da8373531677b1c37a98f53eaa30c892f35e5a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.iplatform.base.util.menu;
 
import com.iplatform.model.vo.MenuVo;
import com.walker.infrastructure.utils.StringUtils;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 新界面菜单树构建对象。
 * @author 时克英
 * @date 2023-05-12
 */
public class MenuTree {
 
    private List<MenuVo> menuList = new ArrayList<>();
 
    public MenuTree(List<MenuVo> menuList) {
        this.menuList = menuList;
    }
 
    //建立树形结构
    public List<MenuVo> buildTree() {
        List<MenuVo> treeMenus = new ArrayList<>();
        for (MenuVo menuNode : getRootNode()) {
            menuNode = buildChildTree(menuNode);
            treeMenus.add(menuNode);
        }
        return sortList(treeMenus);
    }
 
    // 排序
    private List<MenuVo> sortList(List<MenuVo> treeMenus) {
        treeMenus = treeMenus.stream().sorted(Comparator.comparing(MenuVo::getSort).reversed()).collect(Collectors.toList());
        treeMenus.forEach(e -> {
            if (!StringUtils.isEmptyList(e.getChildList())) {
                e.setChildList(sortList(e.getChildList()));
            }
        });
        return treeMenus;
    }
 
    //递归,建立子树形结构
    private MenuVo buildChildTree(MenuVo pNode) {
        List<MenuVo> childMenus = new ArrayList<>();
        for (MenuVo menuNode : menuList) {
            if (menuNode.getPid().equals(pNode.getId())) {
                childMenus.add(buildChildTree(menuNode));
            }
        }
        pNode.setChildList(childMenus);
        return pNode;
    }
 
    //获取根节点
    private List<MenuVo> getRootNode() {
        List<MenuVo> rootMenuLists = new ArrayList<MenuVo>();
        for (MenuVo menuNode : menuList) {
            if (menuNode.getPid().longValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}