构建层级数据

2 篇文章 0 订阅

在这里插入图片描述

// 构建层级列表
    private List<EpAuthUserInfoResponse.Menu> transferMenus(List<?> menus) {
        List<EpAuthUserInfoResponse.Menu> result = new ArrayList<>();

        List<Map> menuTree = buildTree((List<Map>) menus, "0"); // 转成层级数据
        dfsTree(menuTree, result);                                      // DFS 遍历,遍历时转格式
        
        return result;
    }

    public List<Map> buildTree(List<Map> inputList, String rootKey) {

        // 以 parentKey 做索引
        Map<Object, List<Map>> parentMap = inputList.stream().collect(Collectors.groupingBy((json) -> {
            return json.get("superiorFunctionCode");
        }));

        // 遍历List,从parentMap中领养儿子
        inputList.forEach(sub -> {
            // 当前这个节点的所有儿子
            List<Map> children = parentMap.get(sub.get("functionCode"));
            sub.put("children", children);
        });


        // 找到根结点
        List<Map> roots = inputList.stream().filter(v -> (String.valueOf(v.get("superiorFunctionCode")).equals(rootKey)))
                .collect(Collectors.toList());
        return roots;
    }

    // 深度优先遍历树,对所有途径节点转换为所需格式
    // 对于每个节点,先将他转为Menu格式,如果他有children,他的children由dfs方法获得
    // 如果没有children,则到达函数边界 直接添加至上一级的(传入的childrenList)中
    public void dfsTree(List<Map> roots, List<EpAuthUserInfoResponse.Menu> childrenList) {
        for (Map node : roots) {
            // convert current node
            EpAuthUserInfoResponse.Menu menu = convertNode(node);

            childrenList.add(menu);
            if (node.get("children") != null) {
                List<EpAuthUserInfoResponse.Menu> currentNodeChildren = new ArrayList<>();  // 准备一个篮子装这个节点的children
                dfsTree((List<Map>) node.get("children"), currentNodeChildren);
                menu.setChildren(currentNodeChildren);
            }
        }
    }

    public EpAuthUserInfoResponse.Menu convertNode(Map entity) {
        EpAuthUserInfoResponse.Menu menu = new EpAuthUserInfoResponse.Menu();

        menu.setIndex((String) entity.get("id"));
        menu.setRouter((String) entity.get("functionUrl"));
        menu.setName((String) entity.get("functionName"));
        menu.setNameEn((String) entity.get("menuNameEn"));
        menu.setIcon((String) entity.get("menuIcon"));
        menu.setImg((String) entity.get("menuImg"));
        menu.setAlter((String) entity.get("menuAlter"));
        menu.setOrder(StrUtil.toString(entity.get("menuOrder")));
        menu.setMenuCode((String) entity.get("functionCode"));
        menu.setIsHidden((String) entity.get("menuIsHidden"));

        return menu;
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值