数据库中数据结构图
封装数据的实体类
@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
地址:电梯直达