一、问题描述:
最新项目遇到了一个问题,树形结构加载时会超时,后分析后台代码发现,之前写的生成树形结构代码存在bug,当数据量不大时无法触发,一旦数据量比较大就会超时,就在想有没有什么办法能解决这个问题,通过尝试最后整理了一个以空间换时间的方法。
二、解决方案:
1、实体类
@Data
@TableName("Dcx_TargetGroup")
public class DcxTargetGroup implements Serializable {
@TableId(value = "groupId", type = IdType.INPUT)
private Integer groupId;
@TableField("groupName")
private String groupName;
/**
* 上级分组Id
*/
@TableField("parentId")
private Integer parentId = 0;
@TableField(exist = false)
private List<DcxTargetGroup> children;
2、实现方法
/**
* @description 菜单列表转树
* @param list 需要转的对象集合
* @param parentId 根目录id
* @return
*/
public static List<DcxTargetGroup> menuListToTree(List<DcxTargetGroup> list,Integer parentId) {
// 以groupId为key转成map对象集合
Map<Integer, DcxTargetGroup> map = list.stream().collect(Collectors.toMap(DcxTargetGroup::getGroupId, Function.identity()));
// new一个list集合用来存储转完的数据
List<DcxTargetGroup> groups = new ArrayList<>();
for (DcxTargetGroup entity : list) {
// 根目录直接放到新集合第一层
if (entity.getParentId() == parentId) {
groups .add(entity);
} else {
// 非根目录获取到他的上一级
DcxTargetGroup parent = map.get(entity.getParentId());
if (parent != null) {
// 获取到父级对象中的children集合,为空时创建新集合
List<DcxTargetGroup> children = Optional.ofNullable(parent.getChildren()).orElse(new ArrayList<>());
// 把当前对象放入children中
children.add(entity);
// 把children放入parent中
parent.setChildren(children);
} else {
// 获取不到上一级按根目录处理
groups.add(entity);
}
}
}
return groups ;
}
3、方法调用
List<DcxTargetGroup> treeList=TreeUtil.menuListToTree(groupList,0);
三、结束
以上是本人解决方案代码,如果有更好的解决方案,欢迎大家沟通评论点评互相学习,谢谢!!!