网上查了很多关于线性数据转树形结构的文章,这一篇使我受益匪浅,保存备用
工具类
public class TreeUtil{
public static <E extends TreeEntity<E>> List<E> getTreeList(Integer topId, List<E> entityList) {
List<E> resultList=new ArrayList<>();
//获取顶层元素集合
Integer parentId;
for (E entity : entityList) {
parentId=entity.getParentId();
if(parentId==null||topId.equals(parentId)){
resultList.add(entity);
}
}
//获取每个顶层元素的子数据集合
for (E entity : resultList) {
entity.setChildren(getSubList(entity.getId(),entityList));
}
return resultList;
}
private static <E extends TreeEntity<E>> List<E> getSubList(Integer id, List<E> entityList) {
List<E> childList=new ArrayList<>();
Integer parentId;
//子集的直接子对象
for (E entity : entityList) {
parentId=entity.getParentId();
if(id.equals(parentId)){
childList.add(entity);
}
}
//子集的间接子对象
for (E entity : childList) {
entity.setChildren(getSubList(entity.getId(), entityList));
}
//递归退出条件
if(childList.size()==0){
return null;
}
return childList;
}
}
TreeEntity
public interface TreeEntity<E> {
public Integer getId();
public Integer getParentId();
public void setChildren(List<E> children);
}
Entity
实现TreeEntity<E>接口即可
返回数据展示
{
"result": false,
"msg": "查询成功",
"obj": [
{
"id": "1",
"depNo": "1",
"depName": "总部",
"empName": "",
"pid": null,
"changeTime": null,
"children": [
{
"id": "2",
"depNo": "11",
"depName": "销售部",
"empName": null,
"pid": "1",
"changeTime": null,
"children": [
{
"id": "4",
"depNo": "111",
"depName": "销售1部",
"empName": "张三",
"pid": "2",
"changeTime": null,
"children": null
},
{
"id": "5",
"depNo": "112",
"depName": "销售2部",
"empName": null,
"pid": "2",
"changeTime": null,
"children": null
}
]
},
{
"id": "3",
"depNo": "12",
"depName": "人力部",
"empName": null,
"pid": "1",
"changeTime": null,
"children": [
{
"id": "6",
"depNo": "121",
"depName": "人力1部",
"empName": null,
"pid": "3",
"changeTime": null,
"children": null
},
{
"id": "7",
"depNo": "122",
"depName": "人力2部",
"empName": null,
"pid": "3",
"changeTime": null,
"children": null
}
]
}
]
}
],
"code": null
}
我把上述代码进行改造,应用到了项目中
有些地方没有彻底搞懂,像Children的set方法,我没明白怎样在实体类的children中存放List数据,希望大神不吝赐教