Java 实现无限层级的树形结构的数据(使用递归方法)
实现数据结构
{
"code": 200,
"msg": "成功!",
"data": [
{
"id": "3de54a2de215454f84b30f74da895613",
"pid": "-1"
"companyUUId": "5380748e53ee48f8a1b67d34f64c93cf",
"companyId": "ZGBW0001",
"companyName": "xxxx有限公司",
"childrenList": [
{
"id": "202257d84d424db0a3cfd7791e5faf0e",
"pid": "5380748e53ee48f8a1b67d34f64c93cf"
"companyUUId": "2a723da6f60241af911ebe814f0f45f0",
"companyId": "ZGBW000100",
"companyName": "xxxx有限公司",
"childrenList": [
"id": "3258407ffa22434a8f353418f364dc5f",
"pid": "2a723da6f60241af911ebe814f0f45f0"
"companyUUId": "2b653a424a0c4ecdbfcab2d6bf78e160",
"companyId": "ZGBW000199",
"companyName": "xxxx有限公司",
"childrenList": []
]
}
]
}
]
}
1.创建实体类
2、创建返回Vo类
因为我这边使用的是mybatis-plus自带的增删改查方法,所以不能在实体类中新增其他属性
3、查询数据并组装成无线层级树状结构
使用递归方法实现树状结构
public List<AmpCompanyResponse> getCompanyLevel() {
BaseApiService<Object> baseApiService = new BaseApiService<>();
// 查询所有公司
List<AmpCompanyTemporary> AmpList = ampCompanyTemporaryMapper.selectList(new QueryWrapper<AmpCompanyTemporary>().lambda()
.orderByDesc(AmpCompanyTemporary::getCompanyLevel)
.orderByAsc(AmpCompanyTemporary::getId));
// 在此转把List<AmpCompanyTemporary>转换为list<AmpCompanyResponse>
List<AmpCompanyResponse> bList = AmpList.stream().map(ampCompanyTemporary -> {
AmpCompanyResponse ampCompanyResponse = new AmpCompanyResponse();
BeanUtils.copyProperties(ampCompanyTemporary, ampCompanyResponse);
return ampCompanyResponse;
}).collect(Collectors.toList());
// 存放树结构的数据
List<AmpCompanyResponse> ampCompanyTreeList = new ArrayList<>();
if (bList.size() > 0 && bList != null) {
// 找到所有的一级节点存放在一个list中
List<AmpCompanyResponse> parntList = new ArrayList<>();
for (AmpCompanyResponse pList : bList) {
// 父节点的pID为 -1,这边按自己实际情况来判断
if ("-1".equals(pList.getPId())) {
parntList.add(pList);
}
}
// 为一级节点设置子节点 ,getChildren采用递归算法
for (AmpCompanyResponse amp : parntList) {
AmpCompanyResponse companyResponse = new AmpCompanyResponse();
companyResponse = amp;
companyResponse.setChildrenList(getChildren(amp.getCompanyUUId(), bList));
ampCompanyTreeList.add(amp);
}
}
return ampCompanyTreeList;
}
/**
* 递归组装树节点数据
*
* @param id 父节点id
* @param list 所有数据
* @return
*/
public List<AmpCompanyResponse> getChildren(String id, List<AmpCompanyResponse> list) {
List<AmpCompanyResponse> childrenList = new ArrayList<>();
// 子节点
for (AmpCompanyResponse children : list) {
if (id.equals(children.getPId())) {
childrenList.add(children);
}
}
// 把子节点的子节点循环一遍
for (AmpCompanyResponse cList : childrenList) {
cList.setChildrenList(getChildren(cList.getCompanyUUId(),list));
}
return childrenList;
}
效果: