接下来将以下的实体类转换成树形结构
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RuleFunctionDto {
/**
* 显示名称
*/
private String title;
/**
* key值
*/
private String key;
/**
* 子菜单
*/
private List<RuleFunctionDto> children;
/**
* 父id
*/
String parentId;
}
根据parentId 是否等于其的key,来进行划分子类 父类。将子类归类于父类的children中。
如果parentId为空 其便是根节点。
// 将列表转换为树形结构的递归方法
public static List<RuleFunctionDto> buildTree(List<RuleFunctionDto> ruleFunctionDtos) {
// 创建一个映射,用来按key存储RuleFunctionDto
Map<String, RuleFunctionDto> ruleFunctionMap = new HashMap<>();
for (RuleFunctionDto dto : ruleFunctionDtos) {
ruleFunctionMap.put(dto.getKey(), dto);
}
// 存储最终的树形结构
List<RuleFunctionDto> tree = new ArrayList<>();
// 递归函数,用于构建树形结构
buildTreeRecursively(ruleFunctionDtos, tree, ruleFunctionMap, null);
return tree;
}
// 递归构建树形结构
private static void buildTreeRecursively(
List<RuleFunctionDto> allRuleFunctionDtos,
List<RuleFunctionDto> tree,
Map<String, RuleFunctionDto> ruleFunctionMap,
RuleFunctionDto parent) {
for (RuleFunctionDto dto : allRuleFunctionDtos) {
if (BaseUtil.strIsEmpty(dto.getParentId())) {
// 当前dto是根节点
tree.add(dto);
} else {
// 当前dto不是根节点,查找其父节点
RuleFunctionDto parentDto = ruleFunctionMap.get(dto.getParentId());
if (BaseUtil.objNotNull(parentDto)) {
// 将当前dto添加到父节点的children列表中
if (BaseUtil.listIsEmpty(parentDto.getChildren())) {
parentDto.setChildren(new ArrayList<>());
}
parentDto.getChildren().add(dto);
} else {
// 如果找不到父节点,则可能是有问题的数据
log.info("找不到父节点");
}
}
}
}