Java将线形数据结构转换为树形菜单结构2 优化算法 实现时间复杂度为2n 之前为n²

数据库中数据结构图

在这里插入图片描述

封装数据的实体类
@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<>();
    // 使用map保存所有的字段
    HashMap<String, MicroCodeDto> map = new HashMap<>();
    options.forEach(bean -> map.put(bean.getCode(), bean));
    // 查找并填充父子菜单
    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);
            // 找到父菜单
            MicroCodeDto fatherDto = map.get(newStr);
            // 将所有子菜单 填充到父菜单中
            if (!fatherDto.getChild().contains(bean)) {
                fatherDto.getChild().add(bean);
            }
        }
    });
    return result;
}
返回结果展示

在这里插入图片描述

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

猜你喜欢

转载自blog.csdn.net/u010838785/article/details/104023533