返回目录(树结构构造工具)

作为一个小外包...,记录一下工作中常用的一些方法(tools),以便后续使用。
如果有小伙伴看,欢迎指点。但是不要指指点点。。。

这部分代码本质上是一个树结构生成工具。本质是使用stream。这部分代码更多是学习(我只用了若依的表结构,目前代码需要对hutool有一点了解),运用了stream和反射工具(hutool工具中)。
表结构来自于若依管理系统。完整代码点我,git。

核心代码

 /**
     *
     * 造树
     *
     * @param dataList     数据列表
     * @param parentFiled  父节点字段名
     * @param orderByField order by字段名
     * @param childField   子节点名
     * @return {@link List}<{@link T}>

     */
    public static <T> List<T> buildTree(List<T> dataList,  String rootField,String parentFiled, Object rootParentVal,
                                     String orderByField, String childField){
        // 1、筛选出所有父节点
        List<T> parentNodeList = dataList.stream().filter(
                item -> ObjectUtil.equals(ReflectUtil.getFieldValue(item, parentFiled).toString(), String.valueOf(rootParentVal))
        ).collect(Collectors.toList());
        // 2、父节点列表排序
        List<T> sortedList = ListUtil.sortByProperty(parentNodeList, orderByField);
        // 3、构建树形结构的逻辑...
        getChildTree(sortedList, dataList, rootField, parentFiled, orderByField, childField);
        return sortedList;

    }
    
    /**
     *
     * 构造树
     * @param sortedList  排序完的List
     * @param parentFiled 父节点
     * @param dataList 原数据 所有
     */
    private static <T> void getChildTree(List<T> sortedList, List<T> dataList,  String rootField, String parentFiled, String orderByField, String childField) {
        for (T exportOrganization : sortedList) {
            List<T> subList = dataList.stream().filter(o -> Objects.nonNull(ReflectUtil.getFieldValue(o, parentFiled)))
                    .filter(o -> ObjectUtil.equals(StrUtil.toString(ReflectUtil.getFieldValue(o, parentFiled)), StrUtil.toString(ReflectUtil.getFieldValue(exportOrganization, rootField))))
                    .collect(Collectors.toList());
            // 排序
            List<T> ts = ListUtil.sortByProperty(subList, orderByField);
            ReflectUtil.setFieldValue(exportOrganization, childField, ts);
            if (CollectionUtil.isNotEmpty(ts)) {
                getChildTree(ts, dataList, rootField, parentFiled, orderByField, childField);
            }
        }
    }

效果

image.png

主要流程

1、获取当前用户角色信息
2、根据角色获取对应菜单
3、根据菜单父子关系构建树结构

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容