com.rivers.utils.tree.TreeUtil Maven / Gradle / Ivy
package com.rivers.utils.tree;
import com.rivers.utils.dto.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* @author riversking
*/
public class TreeUtil {
/**
* 两层循环实现建树
*
*/
public static List bulid(List treeNodes, Object root) {
List trees = new ArrayList<>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(treeNode);
}
for (T it : treeNodes) {
if (it.getParentId() == treeNode.getId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList());
}
treeNode.add(it);
}
}
}
return trees;
}
/**
* 使用递归方法建树
*
* @param treeNodes treeNodes
* @return
*/
public static List buildByRecursive(List treeNodes, Object root) {
List trees = new ArrayList<>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
}
return trees;
}
/**
* 递归查找子节点
*
* @param treeNodes treeNodes
* @return
*/
public static T findChildren(T treeNode, List treeNodes) {
for (T it : treeNodes) {
if (treeNode.getId() == it.getParentId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList());
}
treeNode.add(findChildren(it, treeNodes));
}
}
return treeNode;
}
}