码迷,mamicode.com
首页 > 编程语言 > 详细

java 实现递归实现tree

时间:2019-01-02 15:04:19      阅读:529      评论:0      收藏:0      [点我收藏+]

标签:nbsp   return   system   eem   menus   void   getch   uid   getmenu   

package app.util;


import java.util.ArrayList;
import java.util.List;


import com.alibaba.fastjson.JSON;


public class Menu {
private Integer pid;
private String menuName;
private Integer parentId;
private Integer position;
private List<Menu> childMenu;


public Integer getPid() {
return pid;
}

 


public void setPid(Integer pid) {
this.pid = pid;
}

 


public String getMenuName() {
return menuName;
}

 


public void setMenuName(String menuName) {
this.menuName = menuName;
}

 


public Integer getParentId() {
return parentId;
}

 


public void setParentId(Integer parentId) {
this.parentId = parentId;
}

 


public Integer getPosition() {
return position;
}

 


public void setPosition(Integer position) {
this.position = position;
}

 


public List<Menu> getChildMenu() {
return childMenu;
}

 


public void setChildMenu(List<Menu> childMenu) {
this.childMenu = childMenu;
}

 

public Menu(Integer pid, String menuName, Integer parentId, Integer position) {
super();
this.pid = pid;
this.menuName = menuName;
this.parentId = parentId;
this.position = position;
}

 

public Menu() {
super();
}

 


public static void main(String[] args) {
List<Menu> treeMenu=new ArrayList<Menu>();

List<Menu> list=new ArrayList<Menu>();
Menu menu1=new Menu(1, "父级1", 0, 1);
Menu menu2=new Menu(2, "父级2", 0, 2);
Menu menu1_1=new Menu(3, "子级1_1", 1, 1);
Menu menu1_2=new Menu(4, "子级1_2", 1, 2);
Menu menu1_2_1=new Menu(5, "子级1_2_1", 4, 2);
list.add(menu1);
list.add(menu2);
list.add(menu1_1);
list.add(menu1_2);
list.add(menu1_2_1);

List<Menu> listTree=buildTree(list,0);

String trssJson=JSON.toJSONString(listTree);
System.out.println(trssJson);

}

public static List<Menu> buildTree(List<Menu> list,int parentId){
List<Menu> menus=new ArrayList<Menu>();
for (Menu menu : list) {

int menuId = menu.getPid();
int pid = menu.getParentId();
if (parentId == pid) {
List<Menu> menuLists = buildTree(list, menuId);

menu.setChildMenu(menuLists);
menus.add(menu);
}
}

return menus;
}
}

java 实现递归实现tree

标签:nbsp   return   system   eem   menus   void   getch   uid   getmenu   

原文地址:https://www.cnblogs.com/-flq/p/10208165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!