java递归父子关系菜单

使用递归操作将父子关系数据转成树形结构对象

前端需要树形结构的json数据,故此 写demo记录下,方便下次查阅。

package tree;

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

/**
* @ClassName Menu
* @Description: TODO
* @Author yuanqingtao
* @Date 2020/11/19
* @Version
**/
public class Menu {

private Integer id;
private Integer parentId;//父id
private String name;//名称
private List<Menu> children;//子集

public Menu() {
}

public Menu(Integer id, Integer parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getParentId() {
return parentId;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Menu> getChildren() {
return children;
}

public void setChildren(List<Menu> children) {
this.children = children;
}

@Override
public String toString() {
return "{" +
"id:" + id +
", parentId:" + parentId +
", name:'" + name + '\'' +
", children:" + children +
'}';
}

public Menu generateTree(Integer id, List<Menu> list) {
Menu root = new Menu();
//查询根
for (Menu menu : list) {
if (menu.getId() == id) {
root = menu;
}
}
//查询子集
List<Menu> childList = new ArrayList<>();
for (Menu node : list) {
if (node.getParentId() == root.getId()) {
childList.add(node);
}
}
//子集查询子集
if (childList != null && childList.size() > 0) {
for (Menu child : childList) {
Menu childRoot = generateTree(child.getId(), list);
if (root.getChildren() == null) {
root.setChildren(new ArrayList<>());
}
root.getChildren().add(childRoot);
}
}
return root;
}

public static void main(String[] args) {
List<Menu> list=new ArrayList<>();
list.add(new Menu(1,0,"上海公司"));
list.add(new Menu(2,1,"二级上海分公司"));
list.add(new Menu(3,2,"三级上海分公司"));
list.add(new Menu(4,1,"二级上海代理公司"));
list.add(new Menu(5,4,"三级上海代理公司"));
list.add(new Menu(6,5,"四级上海代理公司"));

Menu treeJson=new Menu().generateTree(1,list);

System.out.println(treeJson.toString());
}


}

运行结果:{id:1, parentId:0, name:'上海公司', children:[{id:2, parentId:1, name:'二级上海分公司', children:[{id:3, parentId:2, name:'三级上海分公司', children:null}]}, {id:4, parentId:1, name:'二级上海代理公司', children:[{id:5, parentId:4, name:'三级上海代理公司', children:[{id:6, parentId:5, name:'四级上海代理公司', children:null}]}]}]}

json格式化查看结果:

java递归父子关系菜单

 

上一篇:js算法-两种将数组数据转为属性结构记录


下一篇:c#webapi 前端的一些写法