软件编程
位置:首页>> 软件编程>> java编程>> 使用Java将一个List运用递归转成树形结构案例

使用Java将一个List运用递归转成树形结构案例

作者:严老板的博客  发布时间:2021-10-14 15:18:30 

标签:Java,List,递归,树形结构

在开发中,我们会遇到将不同组织架构合并成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、运行结果:

使用Java将一个List运用递归转成树形结构案例

这样list就成功转换成为了tree装结构

来源:https://blog.csdn.net/weixin_36586564/article/details/117918287

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com