将数据库的List转化为Tree
Posted mozq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数据库的List转化为Tree相关的知识,希望对你有一定的参考价值。
将数据库的List转化为Tree
参考
package com.mozq.common.date;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Data
public class DeptNode {
private Integer id;
private Integer parentId;
private String name;
private List<DeptNode> children;
public static List<DeptNode> getTreeFor(List<DeptNode> list, Integer rootId){
List<DeptNode> roots = new ArrayList<>();
//children的值不设置为null
list.forEach(e->e.setChildren(new ArrayList<>()));
for (DeptNode deptNode : list) {
if(deptNode.getParentId().equals(rootId)){
roots.add(deptNode);
}
for (DeptNode node : list) {
//寻找父子关系,为存在关系的建立关系
if(deptNode.getParentId().equals(node.getId())){
if(Objects.isNull(node.getChildren())){
node.setChildren(new ArrayList<>());
}
node.getChildren().add(deptNode);
}
}
}
return roots;
}
public static List<DeptNode> getTree(List<DeptNode> list, Integer rootId){
if(Objects.isNull(list) || list.isEmpty()){
return new ArrayList<>();
}
//获取根列表
List<DeptNode> roots = list.stream().filter(e -> e.getParentId().equals(rootId)).collect(Collectors.toList());
if(roots.isEmpty()){
//return null;
return new ArrayList<>();
}
//为根设置子元素
for (DeptNode root : roots) {
List<DeptNode> children = getTree(list, root.getId());
root.setChildren(children);
}
return roots;
}
public static void main(String[] args) {
List<DeptNode> tree = DeptNode.getTree(data(), 0);
System.out.println(tree);
List<DeptNode> treeFor = DeptNode.getTreeFor(data(), 0);
System.out.println(treeFor);
}
private static List<DeptNode> data(){
DeptNode d1 = new DeptNode();
d1.setName("远眺");
d1.setId(1);
d1.setParentId(0);
DeptNode d2 = new DeptNode();
d2.setName("腾讯");
d2.setId(2);
d2.setParentId(0);
DeptNode d11 = new DeptNode();
d11.setName("研发");
d11.setId(11);
d11.setParentId(1);
DeptNode d12 = new DeptNode();
d12.setName("测试");
d12.setId(12);
d12.setParentId(1);
List<DeptNode> deptNodeList = new ArrayList<>();
deptNodeList.add(d1);
deptNodeList.add(d2);
deptNodeList.add(d11);
deptNodeList.add(d12);
return deptNodeList;
}
}
以上是关于将数据库的List转化为Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 114| Flatten Binary Tree to Linked List(二叉树转化成链表)
[LeetCode] 109. Convert Sorted List to Binary Search Tree
LeetCode Convert Sorted List to Binary Search Tree
LeetCode Convert Sorted List to Binary Search Tree