public class TreeBuilder {
/**
* 两层循环实现建树
* @param treeNodes 传入的树节点列表
* @return
*/
public static List<TreeNode> bulid(List<TreeNode> treeNodes) {
List<TreeNode> trees = new ArrayList<TreeNode>();
for (TreeNode treeNode : treeNodes) {
if ("0".equals(treeNode.getParentResourceId())||treeNode.getParentResourceId().isEmpty()) {
trees.add(treeNode);
}
for (TreeNode it : treeNodes) {
if (it.getParentResourceId() == treeNode.getResourceId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.getChildren().add(it);
}
}
}
return trees;
}
/**
* 使用递归方法建树
* @param treeNodes
* @return
*/
public static List<TreeNode> buildByRecursive(List<TreeNode> treeNodes) {
List<TreeNode> trees = new ArrayList<TreeNode>();
for (TreeNode treeNode : treeNodes) {
if ("0".equals(treeNode.getParentResourceId())||treeNode.getParentResourceId().trim().isEmpty()) {
trees.add(treeNode);
}else {
for (TreeNode tree:trees) {
if(tree.getResourceId().equals(treeNode.getParentResourceId())){
if(tree.getChildren()!=null&&tree.getChildren().size()>0){
List<TreeNode> list = tree.getChildren();
list.add(treeNode);
tree.setChildren(list);
}else{
List<TreeNode> list=new ArrayList<>();
list.add(treeNode);
tree.setChildren(list);
}
break;
}
}
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes
* @return
*/
public static TreeNode findChildren(TreeNode treeNode,List<TreeNode> treeNodes) {
TreeNode tree=new TreeNode();
for (TreeNode it : treeNodes) {
if(treeNode.getResourceId().equals(it.getParentResourceId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.getChildren().add(findChildren(it,treeNodes));
}
}
return treeNode;
}
}