在開(kāi)發(fā)中,我們會(huì)遇到將不同組織架構(gòu)合并成tree這種樹狀結(jié)構(gòu),那么如果做呢?
實(shí)際上,我們也可以理解為如何將擁有父子關(guān)系的list轉(zhuǎn)成樹形結(jié)構(gòu),而這其中主要的方法就是遞歸!
1、實(shí)體對(duì)象:
- @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、轉(zhuǎn)換工具類:
- public class TreeUtils {
- //把一個(gè)List轉(zhuǎn)成樹
- 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,"中國(guó)",-1);
- Node node1=new Node(1,"湖北省",0);
- Node node2=new Node(2,"武漢市",1);
- Node node3=new Node(3,"洪山區(qū)",2);
- Node node4=new Node(4,"宜昌市",1);
- Node node5=new Node(5,"上海市",0);
- Node node6=new Node(6,"靜安區(qū)",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、運(yùn)行結(jié)果:
這樣list就成功轉(zhuǎn)換成為了tree裝結(jié)構(gòu)
到此這篇關(guān)于使用Java將一個(gè)List運(yùn)用遞歸轉(zhuǎn)成樹形結(jié)構(gòu)案例的文章就介紹到這了,更多相關(guān)Java將list運(yùn)用成樹形結(jié)構(gòu)內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_36586564/article/details/117918287