构造工具类:
@UtilityClass
public class TreeUtil {
/**
* 两层循环实现建树
* @param treeNodes 传入的树节点列表
* @return <T extends TreeNode>
*/
public <T extends TreeNode> List<T> build(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(treeNode);
}
for (T it : treeNodes) {
if (it.getParentId().equals(treeNode.getId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<>());
}
treeNode.add(it);
}
}
}
return trees;
}
/**
* 使用递归方法建树
* @param treeNodes 树节点
* @return <T extends TreeNode>
*/
public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes 树节点
* @return <T extends TreeNode>
*/
private <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
for (T it : treeNodes) {
if (treeNode.getId().equals(it.getParentId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<>());
}
treeNode.add(findChildren(it, treeNodes));
}
}
return treeNode;
}
}
实体类:
@Data
public class TreeNode {
protected String id;
protected String parentId;
protected List<TreeNode> children = new ArrayList<TreeNode>();
public void add(TreeNode node) {
children.add(node);
}
}
构造分类树:
@Data
public class SysTreeVo extends TreeNode {
/**
* 名称
*/
private String name;
}
方法:
public List<SysTreeVo> getTreeById(String id) {
QueryWrapper<SysTreeNode> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("tree_id", id);
List<SysTreeNode> listTreeNode = this.selectList(queryWrapper);
//排序和赋值
List<SysTreeVo> listTree = listTreeNode.stream()
.sorted(Comparator.comparing(SysTreeNode::getSn))
.map(sysTreeNode -> {
SysTreeVo sysTreeVo = new SysTreeVo();
BeanUtils.copyProperties(sysTreeNode, sysTreeVo);
return sysTreeVo;
}).collect(Collectors.toList());
//构造树
List<SysTreeVo> trees = TreeUtil.build(listTree, "-1");
return trees;
}
格式:
{
"code": 0,
"msg": null,
"data": [
{
"id": "20210412161821381517625027760128",
"parentId": "-1",
"children": [
{
"id": "20210412161821381517908621430784",
"parentId": "20210412161821381517625027760128",
"children": [
{
"id": "20210412161821381518025118224384",
"parentId": "20210412161821381517908621430784",
"children": [],
"name": "测试分类树12节点"
},
{
"id": "20210412161821381518058270003200",
"parentId": "20210412161821381517908621430784",
"children": [],
"name": "测试分类树12节点"
}
],
"name": "测试分类树11节点"
},
{
"id": "20210412161821381517804485251072",
"parentId": "20210412161821381517625027760128",
"children": [],
"name": "测试分类树1节点"
}
],
"name": "测试分类树1"
}
]
}