Java将线形数据结构转换为树形菜单结构

数据库中数据结构图

在这里插入图片描述

封装数据的实体类
@Data
public class MicroCodeDto {
    private String id;
    private String code;
    private String name;
    private List<MicroCodeDto> child = new ArrayList<>();

    public MicroCodeDto(String id, String code, String name) {
        this.id = id;
        this.code = code;
        this.name = name;
    }
}
解析方法
public static Object formatXDMCheckOptions(List<MicroCodeDto> options) {
    ArrayList<MicroCodeDto> result = new ArrayList<>();
    options.forEach(bean -> {
        // 获取最后一个'.'的index
        int index = bean.getCode().lastIndexOf(".");
        // 没有'.'说明是顶级菜单
        if (index == -1) {
            result.add(bean);
        } else if (index + 1 < bean.getCode().length()) {
            // 子菜单 用最后一个点 分割 找到父菜单code
            String newStr = bean.getCode().substring(0, index);
            options.forEach(bean2 -> {
                // 将所有子菜单 填充到父菜单中
                if (bean2.getCode().equals(newStr) && !bean2.getChild().contains(bean)) {
                    bean2.getChild().add(bean);
                }
            });
        }
    });
    return result;
}
返回结果展示

在这里插入图片描述

该算法时间复杂度为n² 优化后的时间复杂度为2n
地址:电梯直达

发布了200 篇原创文章 · 获赞 97 · 访问量 59万+

猜你喜欢

转载自blog.csdn.net/u010838785/article/details/104021689
今日推荐