1.导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId><version>5.8.36</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
</dependencies>
2.准备数据
3.构建数据
@RequestMapping("/test2")public Object test2() {// 准备数据List<Department> departments = new ArrayList<>();departments.add(new Department(1L, 0L, "总公司", "1",0,123));departments.add(new Department(2L, 1L, "研发部","2",11,456));departments.add(new Department(3L, 1L, "市场部","3",9,789));departments.add(new Department(4L, 2L, "后端组","4",18,112));departments.add(new Department(5L, 2L, "前端组","5",15,167));List<Tree<Long>> tree1 = TreeUtil.build(departments, 0L,(treeNode, tree) -> {tree.setId(treeNode.getId());tree.setName(treeNode.getName());tree.setParentId(treeNode.getParentId());});return tree1;}
方法参数说明:
- TreeUtil.build(数据集合, 根节点ID, 树节点配置, 节点转换器)
- 数据集合:需要转换的原始数据列表(如 departments)
- 根节点ID:顶级节点的父ID值(示例中 0L 表示总公司为根)
- 树节点配置:TreeNodeConfig 可自定义字段映射(可选参数)
- 节点转换器:BiConsumer 用于设置节点属性
代码示例分析
TreeUtil.build(departments, 0L, (treeNode, tree) -> {tree.setId(treeNode.getId());tree.setName(treeNode.getName());tree.setParentId(treeNode.getParentId());
})未传入 TreeNodeConfig 参数,采用默认字段映射:
* id 字段:id
* parentId 字段:parentId
* 子节点字段:children
* 权重字段:weight
更改默认字段
添加额外的字段,可以是对象,集合
注意事项
- 数据对象必须包含 id 和 parentId 字段
- parentId的值需与某个节点的 id 匹配(根节点 parentId 需与参数中的根ID一致)
- 确保数据中没有循环引用(如 A 的 parent 是 B,B 的 parent 又是 A)
总结:通过该工具类可快速将扁平列表转换为嵌套树结构,适用于菜单、组织架构等场景。