在开发中,我们会遇到将不同组织架构合并成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装结构
到此这篇关于使用Java将一个List运用递归转成树形结构案例的文章就介绍到这了,更多相关Java将list运用成树形结构内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_36586564/article/details/117918287