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

数据库中数据结构图

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

封装数据的实体类
@Data
public class MicroCodeDto {
    private String id;
    private String code;
    private String name;
    private List 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 options) {
    ArrayList result = new ArrayList<>();
    // 使用map保存所有的字段
    HashMap 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;
}
返回结果展示

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

你可能感兴趣的:(JavaEE,工具类)