作者:卖女孩的小方子 | 来源:互联网 | 2023-09-24 09:57
项目开发中,几乎无法避免的会遇到树形结构,今天和大家分享java后端如何处理数据为树形结构。
1.封装测试实体类
package com.ldl.cn.demo;
import java.util.ArrayList;
import java.util.List;
public class Dept {
private int id;
private int parentId;
private String name;
private List child = new ArrayList();
public Dept() {
super();
}
public Dept(int id, int parentId, String name) {
super();
this.id = id;
this.parentId = parentId;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getChild() {
return child;
}
public void setChild(List child) {
this.child = child;
}
@Override
public String toString() {
return " [id=" + id + ", parentId=" + parentId + ", name=" + name + ", child=" + child + "]";
}
}
需要注意文中加粗属性。
2.编写测试类
package com.ldl.cn.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.hutool.json.JSONUtil;
public class TestDemo {
private static List deptList;
static {
Dept dept1 = new Dept(1, 0, "中国");
Dept dept2 = new Dept(2, 1, "北京");
Dept dept3 = new Dept(3, 1, "上海");
Dept dept4 = new Dept(4, 1, "广东");
Dept dept5 = new Dept(5, 4, "广州");
Dept dept6 = new Dept(6, 4, "深圳");
Dept dept7 = new Dept(7, 5, "天河区");
deptList = new ArrayList();
deptList.add(dept1);
deptList.add(dept2);
deptList.add(dept3);
deptList.add(dept4);
deptList.add(dept5);
deptList.add(dept6);
deptList.add(dept7);
}
private static List buildTree(List deptList,int pid){
List treeList = new ArrayList();
for (Dept dept : deptList) {
if (dept.getParentId() == pid) {
dept.setChild(buildTree(deptList, dept.getId()));
treeList.add(dept);
}
}
return treeList;
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("data", buildTree(deptList, 1));
System.out.println(JSONUtil.toJsonStr(map));
}
}
读者可以自行体会加粗递归方法。
3.运行结果与分析
控制台输出:
{"data":[{"name":"北京","id":2,"parentId":1,"child":[]},{"name":"上海","id":3,"parentId":1,"child":[]},{"name":"广东","id":4,"parentId":1,"child":[{"name":"广州","id":5,"parentId":4,"child":[{"name":"天河区","id":7,"parentId":5,"child":[]}]},{"name":"深圳","id":6,"parentId":4,"child":[]}]}]}
使用JSON解析工具解析:
成功组装树形结构!