无序的List<MenuTree<T>> nodes集合生成List<MenuTree<T>> 树
无序的List<DeptTree<T>> nodes集合生成List<DeptTree<T>>树
无序的List<MenuTree<T>> nodes集合根据idParam参数作为pid,来生成其下的List<MenuTree<T>> 树
package cc.mrbird.febs.common.utils;
import cc.mrbird.febs.common.entity.DeptTree;
import cc.mrbird.febs.common.entity.MenuTree;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author MrBird
*/
public class TreeUtil {
//顶层节点
private static final String TOP_NODE_ID = "0";
public static <T> MenuTree<T> buildMenuTree(List<MenuTree<T>> nodes) {
if (nodes == null) {
return null;
}
//顶层节点集合
List<MenuTree<T>> topNodes = new ArrayList<>();
//遍历集合
nodes.forEach(children -> {
String pid = children.getParentId();
//如果pid为空或者pid为0
if (pid == null || TOP_NODE_ID.equals(pid)) {
//将节点添加到顶层节点集合中
topNodes.add(children);
return;
}
//如果pid不为空或者pid不为0
for (MenuTree<T> parent : nodes) {
String id = parent.getId();
//如果id不为空或者id等于pid
if (id != null && id.equals(pid)) {
//将子节点添加到父节点的childs字段的list集合中
parent.getChilds().add(children);
//子节点有父
children.setHasParent(true);
//父节点有子
parent.setHasChild(true);
return;
}
}
});
//根节点
MenuTree<T> root = new MenuTree<>();
root.setId(TOP_NODE_ID);//设置根节点id为0
root.setParentId(StringUtils.EMPTY);//设置根节点pid为null
root.setHasParent(false);//设置根节点无父节点
root.setHasChild(true);//设置根节点有子节点
root.setChecked(true);//设置childs集合
root.setChilds(topNodes);
Map<String, Object> state = new HashMap<>(16);
root.setState(state);
return root;
}
public static <T> List<DeptTree<T>> buildDeptTree(List<DeptTree<T>> nodes) {
if (nodes == null) {
return null;
}
//顶层节点集合
List<DeptTree<T>> result = new ArrayList<>();
//遍历集合
nodes.forEach(children -> {
String pid = children.getParentId();
//如果pid为空或者pid为0
if (pid == null || TOP_NODE_ID.equals(pid)) {
//将节点添加到顶层节点集合中
result.add(children);
return;
}
//如果pid不为空或者pid不为0
for (DeptTree<T> n : nodes) {
String id = n.getId();
//如果id不为空或者id等于pid
if (id != null && id.equals(pid)) {
//与MenuTree<T>类有所不同,MenuTree<T>类被使用时,childs字段的list集合已经初始化了
//而DeptTree<T>类在被调用时,其childs字段的list集合还未初始化,所以在向childs的list集合中添加节点前需要先进行初始化
if (n.getChildren() == null) {
n.initChildren();
}
//将子节点添加到父节点的childs字段的list集合中
n.getChildren().add(children);
//子节点有父
children.setHasParent(true);
//父节点有子
n.setHasChild(true);
return;
}
}
});
return result;
}
//查询idParam节点下的所有节点
public static <T> List<MenuTree<T>> buildList(List<MenuTree<T>> nodes, String idParam) {
if (nodes == null) {
return new ArrayList<>();
}
List<MenuTree<T>> topNodes = new ArrayList<>();
//遍历节点
nodes.forEach(children -> {
String pid = children.getParentId();
//pid为null或idParam等于pid
if (pid == null || idParam.equals(pid)) {
topNodes.add(children);
return;
}
nodes.forEach(parent -> {
String id = parent.getId();
if (id != null && id.equals(pid)) {
parent.getChilds().add(children);
children.setHasParent(true);
parent.setHasChild(true);
}
});
});
return topNodes;
}
}