1、项目需求:
从数据库从加载所有的菜单出来,菜单中有
id,parentId,name字段
希望能有一个工具帮我进行树形结构重组;
实例类:
package com.lming.chcservice.util;
import lombok.Data;
import java.util.List;
@Data
public class TreeNode {
/**
* 节点id
*/
private String id;
/**
* 父节点 默认0为根节点
*/
private String parentId;
/**
* 节点名称
*/
private String name;
/**
* 是否有子节点
*/
private boolean hasChild;
public TreeNode(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
}
package com.lming.chcservice.util;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 树形结构工具类
*
* 将一组list对象转成树形结构
* 该list需符合设定的字段类型
*
*/
public class TreeUtil {
public static Map mapArray = new LinkedHashMap();
public List menuCommon;
public List
测试结果:
[
{
"id": "1",
"name": "首页",
"parentId": "0",
"hasChild": true,
"childrens": [
{
"id": "3",
"name": "预约",
"parentId": "1",
"hasChildren": false,
"childrens": []
}
]
},
{
"id": "2",
"name": "订单",
"parentId": "0",
"hasChild": true,
"childrens": [
{
"id": "4",
"name": "捐献",
"parentId": "2",
"hasChild": true,
"childrens": [
{
"id": "5",
"name": "我的订单",
"parentId": "4",
"hasChild": true,
"childrens": [
{
"id": "6",
"name": "个人中心",
"parentId": "5",
"hasChild": true,
"childrens": [
{
"id": "7",
"name": "个人中心2",
"parentId": "6",
"hasChildren": false,
"childrens": []
}
]
}
]
}
]
}
]
}
]
实力类不一致怎么办? 自己写一个实体转换类,将类的对象属性转换成上面的实体类,然后在调用,当然最快的方式直接修改实体类即可用。