根据父id 搭建树形结构,List转变

接下来将以下的实体类转换成树形结构

@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("找不到父节点");
}
}
}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值