通用树形结构工具类
/**
* @author qiaoyp
* @company csdn
* @Date 2022/12/15 10:04
*/
public class TreeUtils {
public static <T extends Tree<T>> List<T> getTree(List<T> nodes, String rootNodeId) {
List<T> treeList = new ArrayList<>();
if (nodes == null || nodes.isEmpty()) {
return treeList;
}
// 根点集合
List<T> rootNodes = new ArrayList<>();
// 子节点集合
List<T> childNodes = new ArrayList<>();
nodes.forEach(node-> {
String parentId = node.getParentId();
// 当父节点为0时 当前节点为根节点
if (parentId.equals(rootNodeId)) {
rootNodes.add(node);
} else {
childNodes.add(node);
}
});
rootNodes.forEach(rootNode -> addChilds(rootNode, childNodes));
return rootNodes;
}
/**
* 为父节点添加所有的子节点
* 一次性获取父节点的所有子节点(然后遍历子节点,把当前子节点当作父节点,为该节点再添加子节点)
* @param parentNode 当前节点
* @param childNodes 所有的节点
*/
private static <T extends Tree<T>> void addChilds(T parentNode, List<T> childNodes) {
List<T> childs = getChildren(parentNode, childNodes);
if (!childs.isEmpty()) {
parentNode.setChildren(childs);
//为每一个子节点获取所有的自己的子节点
childs.forEach(pNode -> addChilds(pNode, childNodes));
}
}
/**
* 获取父节点的所有直接子节点
*/
private static <T extends Tree<T>> List<T> getChildren(T parentNode, List<T> childNodes) {
if (CollectionUtils.isEmpty(childNodes)) {
return Collections.emptyList();
}
String id = parentNode.getId();
List<T> nextNodes = new ArrayList<>();
for (T childNode : childNodes) {
String parentId = childNode.getParentId();
if (id.equals(parentId)) {
nextNodes.add(childNode);
}
}
return nextNodes;
}
}