java 实现递归实现tree

  1 package com.bert.logic;
  2 
  3 
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 
  7 
  8 import com.alibaba.fastjson.JSON;
  9 
 10 
 11 public class Menu {
 12 private Integer pid;
 13 private String menuName;
 14 private Integer parentId;
 15 private Integer position;
 16 private List<Menu> childMenu;
 17 
 18 
 19 public Integer getPid() {
 20 return pid;
 21 }
 22 
 23 
 24 
 25 
 26 public void setPid(Integer pid) {
 27 this.pid = pid;
 28 }
 29 
 30 
 31 
 32 
 33 public String getMenuName() {
 34 return menuName;
 35 }
 36 
 37 
 38 
 39 
 40 public void setMenuName(String menuName) {
 41 this.menuName = menuName;
 42 }
 43 
 44 
 45 
 46 
 47 public Integer getParentId() {
 48 return parentId;
 49 }
 50 
 51 
 52 
 53 
 54 public void setParentId(Integer parentId) {
 55 this.parentId = parentId;
 56 }
 57 
 58 
 59 
 60 
 61 public Integer getPosition() {
 62 return position;
 63 }
 64 
 65 
 66 
 67 
 68 public void setPosition(Integer position) {
 69 this.position = position;
 70 }
 71 
 72 
 73 
 74 
 75 public List<Menu> getChildMenu() {
 76 return childMenu;
 77 }
 78 
 79 
 80 
 81 
 82 public void setChildMenu(List<Menu> childMenu) {
 83 this.childMenu = childMenu;
 84 }
 85 
 86 
 87 
 88 public Menu(Integer pid, String menuName, Integer parentId, Integer position) {
 89 super();
 90 this.pid = pid;
 91 this.menuName = menuName;
 92 this.parentId = parentId;
 93 this.position = position;
 94 }
 95 
 96 
 97 
 98 public Menu() {
 99 super();
100 }
101 
102 
103 
104 
105 public static void main(String[] args) {
106 List<Menu> treeMenu=new ArrayList<Menu>();
107 
108 List<Menu> list=new ArrayList<Menu>();
109 Menu menu1=new Menu(1, "父级1", 0, 1);
110 Menu menu2=new Menu(2, "父级2", 0, 2);
111 Menu menu1_1=new Menu(3, "子级1_1", 1, 1);
112 Menu menu1_2=new Menu(4, "子级1_2", 1, 2);
113 Menu menu1_2_1=new Menu(5, "子级1_2_1", 4, 2);
114 list.add(menu1);
115 list.add(menu2);
116 list.add(menu1_1);
117 list.add(menu1_2);
118 list.add(menu1_2_1);
119 
120 List<Menu> listTree=buildTree(list,0);
121 
122 String trssJson=JSON.toJSONString(listTree);
123 System.out.println(trssJson);
124 
125 }
126 
127 public static List<Menu> buildTree(List<Menu> list,int parentId){
128 List<Menu> menus=new ArrayList<Menu>();
129       for (Menu menu : list) {  
130   
131           int menuId = menu.getPid();
132           int pid = menu.getParentId();
133           if (parentId == pid) {  
134               List<Menu> menuLists = buildTree(list, menuId);  
135               
136               menu.setChildMenu(menuLists);
137               menus.add(menu);  
138           }  
139       }  
140      
141 return menus;
142 }
143 }

 

posted @ 2018-06-01 16:39  劉先生  阅读(6183)  评论(0编辑  收藏  举报