在做目录树的时候通常是将一个目录存在数据库的List全部返回来,再根据节点id和parentId组装成一颗树。
List转成Tree有两种方式,一种是常用的递归,一种是双层循环。(建议递归)
package com.gysoft.utils.tree;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/**
* @Description:
* @Date: 2019/9/19 17:20
* @Author: WangLingJi
*/
@Data
@ToString
public class TreeNode {
private String id;
private String parentId;
private String name;
private List<TreeNode> children;
public TreeNode(String id, String name, String parentId) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public TreeNode(String id, String name, TreeNode parent) {
this.id = id;
this.parentId = parent.getId();
this.name = name;
}
}
/**
* 双重for循环
*/
public static List<TreeNode> foreachTest(List<TreeNode> treeNodes) {
List<TreeNode> trees = new ArrayList<>();
treeNodes.forEach(treeNode -> {
if ("0".equals(treeNode.getParentId())) {
trees.add(treeNode);
}
treeNodes.forEach(treeNode1 -> {
if (treeNode1.getParentId().equals(treeNode.getId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<>());
}
treeNode.getChildren().add(treeNode1);
}
});
});
return trees;
}
/**
* 使用递归方法建树
*/
public static List<TreeNode> recursiveTest(List<TreeNode> treeNodes) {
List<TreeNode> trees = new ArrayList<>();
treeNodes.forEach(treeNode -> {
if ("0".equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
});
return trees;
}
/**
* 递归查找子节点
*/
public static TreeNode findChildren(TreeNode treeNode, List<TreeNode> treeNodes) {
treeNodes.forEach(treeNode1 -> {
if (treeNode.getId().equals(treeNode1.getParentId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<>());
}
treeNode.getChildren().add(findChildren(treeNode1, treeNodes));
}
});
return treeNode;
}
public static void main(String[] args) throws Exception{
TreeNode treeNode1 = new TreeNode("1", "广州", "0");
TreeNode treeNode2 = new TreeNode("2", "深圳", "0");
TreeNode treeNode3 = new TreeNode("3", "天河区", treeNode1);
TreeNode treeNode4 = new TreeNode("4", "越秀区", treeNode1);
TreeNode treeNode5 = new TreeNode("5", "黄埔区", treeNode1);
TreeNode treeNode6 = new TreeNode("6", "石牌", treeNode3);
TreeNode treeNode7 = new TreeNode("7", "百脑汇", treeNode6);
TreeNode treeNode8 = new TreeNode("8", "南山区", treeNode2);
TreeNode treeNode9 = new TreeNode("9", "宝安区", treeNode2);
TreeNode treeNode10 = new TreeNode("10", "科技园", treeNode8);
List<TreeNode> list= Stream.of(treeNode1,treeNode2,treeNode3,treeNode4,treeNode5,treeNode6,treeNode7,treeNode8,treeNode9,treeNode10).collect(Collectors.toList());
List<TreeNode> trees = foreachTest(list);
trees.forEach(System.out::println);
System.out.println("------------------华丽的分割线-----------------------");
List<TreeNode> trees2 = recursiveTest(list);
trees2.forEach(System.out::println);
}
|