Java非递归实现有序菜单树_菜单树的java实现(菜单非递归实现)-Go语言中文社区...

菜单树

在web开发中我们经常会遇到菜单的问题,那么如何去实现一个菜单树呢?很多人可能第一反应就是递归,因为菜单是可能是无限级的,那么能不能不用递归就实现一个菜单树呢?

要实现的效果图,如下:

Java非递归实现有序菜单树_菜单树的java实现(菜单非递归实现)-Go语言中文社区..._第1张图片

class ThreeBean{

private String id; //节点id

private String parentId; //父节点id

private String name;  //节点名称

private List children = new ArrayList();//子节点

private Double count; //节点对应的数量

private Boolean expanded=false;//是否有子节点

public static void main(String[] args) {

Map nodeListMap = new HashMap();

ThreeBean root=new ThreeBean("0",null,"根节点",0D);

nodeListMap.put(root.getId(), root);

ThreeBean a1=new ThreeBean("1","0","节点1",0D);

nodeListMap.put(a1.getId(), a1);

ThreeBean a2=new ThreeBean("2","0","节点2",0D);

nodeListMap.put(a2.getId(), a2);

ThreeBean a3=new ThreeBean("3","1","节点3",0D);

nodeListMap.put(a3.getId(), a3);

ThreeBean a4=new ThreeBean("4","2","节点4",0D);

nodeListMap.put(a4.getId(), a4);

ThreeBean a5=new ThreeBean("5","2","节点5",0D);

nodeListMap.put(a5.getId(), a5);

ThreeBean a6=new ThreeBean("6","3","节点6",1D);

nodeListMap.put(a6.getId(), a6);

ThreeBean a7=new ThreeBean("7","3","节点7",2D);

nodeListMap.put(a7.getId(), a7);

ThreeBean a8=new ThreeBean("8","3","节点8",3D);

nodeListMap.put(a8.getId(), a8);

ThreeBean a9=new ThreeBean("9","4","节点9",4D);

nodeListMap.put(a9.getId(), a9);

ThreeBean a10=new ThreeBean("10","4","节点10",5D);

nodeListMap.put(a10.getId(), a10);

ThreeBean a11=new ThreeBean("11","4","节点11",6D);

nodeListMap.put(a11.getId(), a11);

ThreeBean a12=new ThreeBean("12","4","节点12",7D);

nodeListMap.put(a12.getId(), a12);

ThreeBean a13=new ThreeBean("13","5","节点13",8D);

nodeListMap.put(a13.getId(), a13);

ThreeBean a14=new ThreeBean("14","5","节点14",9D);

nodeListMap.put(a14.getId(), a14);

for (String key:nodeListMap.keySet())

{

ThreeBean nodeData = nodeListMap.get(key);

//主键是空的则为根目录 根据自己情况定义根目录

if (nodeData.getParentId() == null || nodeData.getParentId().equals("")) {

root = nodeData;

root.setExpanded(true);

}

else

{

//根据该目录的父节点组合其子节点集合

ThreeBean zTreeDataInfo =nodeListMap.get(nodeData.getParentId());

zTreeDataInfo.getChildren().add(nodeData);

zTreeDataInfo.setExpanded(true);

}

}

//到这里的话 我们就构造了完了 二叉树

ObjectMapper mapper = new ObjectMapper();

String json = null;

root=count(root);

try {

json = mapper.writeValueAsString(root);

} catch (JsonProcessingException e) {

e.printStackTrace();

}

System.out.println(json);

}

private static ThreeBean count(ThreeBean root){//递归给节点赋值

Double total = root.getCount();

if(root.getChildren().size() < 1){

root.setCount(total);

return root;

}

Double sum = total;

for(ThreeBean child : root.getChildren()){

ThreeBean tmp = count(child);

sum += tmp.getCount();

}

root.setCount(sum);

return root;

}

}

总结:这种实现菜单树的方法应该要比递归简单容易理解。

你可能感兴趣的:(Java非递归实现有序菜单树)