使用Java将一个List运用递归转成树形结构案例
作者:严老板的博客 时间:2021-10-14 15:18:30
在开发中,我们会遇到将不同组织架构合并成tree这种树状结构,那么如果做呢?
实际上,我们也可以理解为如何将拥有父子关系的list转成树形结构,而这其中主要的方法就是递归!
1、实体对象:
@Data
public class Node {
private Integer id;
private String city;
private Integer pid;
private List<Node> children;
public Node(Integer id,String city,Integer pid){
this.id = id;
this.city = city;
this.pid = pid;
}
}
2、转换工具类:
public class TreeUtils {
//把一个List转成树
static List<Node> buildTree(List<Node> list,Integer pid){
List<Node> tree=new ArrayList<>();
for(Node node:list){
if(Objects.equals(node.getPid(),pid)){
tree.add(findChild(node,list));
}
}
return tree;
}
static Node findChild(Node node, List<Node> list){
for(Node n:list){
if(Objects.equals(n.getPid(),node.getId())){
if(node.getChildren() == null){
node.setChildren(new ArrayList<Node>());
}
node.getChildren().add(findChild(n,list));
}
}
return node;
}
public static void main(String[] args) {
Node node0=new Node(0,"中国",-1);
Node node1=new Node(1,"湖北省",0);
Node node2=new Node(2,"武汉市",1);
Node node3=new Node(3,"洪山区",2);
Node node4=new Node(4,"宜昌市",1);
Node node5=new Node(5,"上海市",0);
Node node6=new Node(6,"静安区",5);
List<Node> list=new ArrayList<>();
list.add(node3);
list.add(node4);
list.add(node1);
list.add(node2);
list.add(node5);
list.add(node6);
list.add(node0);
List<Node> nodes = buildTree(list,-1);
System.out.println(JSON.toJSONString(nodes));
}
}
3、运行结果:
这样list就成功转换成为了tree装结构
来源:https://blog.csdn.net/weixin_36586564/article/details/117918287
标签:Java,List,递归,树形结构
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
android仿微信联系人索引列表功能
2023-06-22 17:33:30
![](https://img.aspxhome.com/file/2023/2/83512_0s.gif)
c#数组详解
2023-01-31 13:09:08
Mybatis Log Plugin的使用方式
2021-08-27 19:02:31
![](https://img.aspxhome.com/file/2023/8/61828_0s.jpg)
Spring代理对象导致的获取不到原生对象注解的解决
2021-12-05 11:44:19
JAVA 中Spring的@Async用法总结
2023-11-28 16:35:58
java实现zip,gzip,7z,zlib格式的压缩打包
2023-08-13 08:56:59
javaweb Servlet开发总结(二)
2023-10-31 11:51:48
![](https://img.aspxhome.com/file/2023/7/58567_0s.png)
Java实现简单登陆界面
2022-11-25 05:47:47
![](https://img.aspxhome.com/file/2023/8/63398_0s.png)
Java操作hdfs文件系统过程
2023-12-13 23:42:32
![](https://img.aspxhome.com/file/2023/7/70967_0s.png)
Java 分割字符串详解及实例代码
2023-11-29 13:18:42
Spring @Conditional通过条件控制bean注册过程
2023-08-06 10:00:11
SpringBoot过滤器与拦截 器深入分析实现方法
2023-11-28 23:04:15
Java SpringMVC数据响应超详细讲解
2022-04-08 15:10:26
![](https://img.aspxhome.com/file/2023/1/63161_0s.png)
JavaCV实现照片马赛克效果
2023-04-27 15:55:14
![](https://img.aspxhome.com/file/2023/4/66624_0s.jpg)
Spring 报错:元素 "context:component-scan" 的前缀 "context" 未绑定的问题解决
2023-09-10 07:45:34
JAVA演示阿里云图像识别API,印刷文字识别-营业执照识别
2022-04-21 15:05:22
Java线程并发中常见的锁机制详细介绍
2023-07-04 05:33:33
![](https://img.aspxhome.com/file/2023/9/70339_0s.png)
java 线程方法join简单用法实例总结
2022-10-26 19:27:38
Java+MySQL 图书管理系统
2023-11-28 19:28:43
![](https://img.aspxhome.com/file/2023/7/60757_0s.png)
android TextView设置中文字体加粗实现方法
2023-08-06 02:32:03