利用栈来实现权限树
权限树结构
java中提供了对应的栈结构来进行操作
private static void pop() {
List<String> stringList = Arrays.asList("1", "2", "3", "4");
Stack<String> stack = new Stack<>();
stack.addAll(stringList);
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
测试输出发现输出顺序是:4、3、2、1。添加顺序是1、2、3、4
那么来测试一下对应的权限树结构:
public class TreeNode {
public TreeNode() {
}
public TreeNode(Integer id, Integer parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
private Integer id;
private Integer parentId;
private String name;
private List<TreeNode> treeNodeList = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TreeNode> getTreeNodeList() {
return treeNodeList;
}
public void setTreeNodeList(List<TreeNode> treeNodeList) {
this.treeNodeList = treeNodeList;
}
@Override
public String toString() {
return "TreeNode{" +
"id=" + id +
", parentId=" + parentId +
", name='" + name + '\'' +
", treeNodeList=" + treeNodeList +
'}';
}
}
对应的测试类:
public class TestOne {
public static void main(String[] args) {
List<TreeNode> treeNodeList = new ArrayList<>();
treeNodeList.add(new TreeNode(1, 0, "根节点"));
treeNodeList.add(new TreeNode(2, 1, "根节点的子节点1"));
treeNodeList.add(new TreeNode(3, 1, "根节点的子节点2"));
treeNodeList.add(new TreeNode(4, 3, "根节点的子节点2的子节点1"));
treeNodeList.add(new TreeNode(5, 4, "根节点的子节点2的子节点的子节点"));
treeNodeList.add(new TreeNode(6, 3, "根节点的子节点2的子节点2"));
Map<Integer, List<TreeNode>> collect = treeNodeList.stream().collect(Collectors.groupingBy(TreeNode::getParentId));
System.out.println(collect);
// 获取得到根节点
List<TreeNode> collect1 = treeNodeList.stream().filter(treeNode -> treeNode.getParentId() == 0).collect(Collectors.toList());
Stack<TreeNode> stack = new Stack<>();
stack.addAll(collect1);
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
List<TreeNode> treeNodes = collect.get(pop.getId());
if (treeNodes != null && treeNodes.size() > 0) {
pop.setTreeNodeList(treeNodes);
stack.addAll(treeNodes);
}
}
System.out.println(collect1);
}
private static void pop() {
List<String> stringList = Arrays.asList("1", "2", "3", "4");
Stack<String> stack = new Stack<>();
stack.addAll(stringList);
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
查看对应的结点可以看到对应的输出信息,形成了一棵树结构。
从理论中来,到实践中去,最终回归理论