首页 > 图灵资讯 > 技术篇>正文
Java树结构递归生成效率低下如何优化?
2025-03-07 21:09:01
深入分析树结构递归优化战略
递归生成树结构数据用于祖传代码,效率低下。本文将优化以下java代码片段,提高树结构生成效率。
public list<map> creategrouptreenode() { list<map> childrenlist = new arraylist<map>(); getchildlist(0l,childrenlist); list<map> treelist = new arraylist<map>(); map map = new hashmap(); map.put("id", 0); map.put("text","根节点"); map.put("isleaf", "0"); map.put("icon", "fa fa-folder"); map submap = new hashmap(); submap.put("opened", true); submap.put("selected", true); map.put("state", submap); map.put("children", childrenlist); treelist.add(map); return treelist; } public list<map> getchildlist(long id,list<map> childrenlist){ list<basegroup> childlist = basemapper.childlistbyparentid(id); if(childlist != null && childlist.size() > 0){ list<map> tempmap = new arraylist<map>(); for(int i = 0; i < childlist.size(); i++){ list<map> mylist = getchildlist(childlist.get(i).getid(),childrenlist); map map = new hashmap(); if(mylist == null){ map.put("id", childlist.get(i).getid()); map.put("text", childlist.get(i).getnumber() + " - " + childlist.get(i).getname()); map.put("isleaf", "1"); map.put("icon", "fa fa-folder"); map submap = new hashmap(); submap.put("opened", false); map.put("state", submap); tempmap.add(map); }else{ map.put("id", childlist.get(i).getid()); map.put("text", childlist.get(i).getnumber() + " - " + childlist.get(i).getname()); map.put("isleaf", "0"); map.put("icon", "fa fa-folder"); map.put("children", mylist); map submap = new hashmap(); submap.put("opened", false); map.put("state", submap); tempmap.add(map); } if(id == 0){ childrenlist.add(map); } } return tempmap; } return null; }
在这个代码中,getchildlist方法存在效率问题。首先,childrenlist参数作为输出参数,仅在id中 == 使用0l时,这会导致不必要的参数传递。这种方法的返回值可以直接用于删除参数。
其次,在getchildlist方法的循环中,反复调用childlist.get(i)降低效率。在中间变量缓存循环中引入元素,或使用增强for循环进行优化。
最后,在for循环中的if分支中,大多数代码都是相同的,只有isleaf和children字段不同,我们可以提取重复的代码,只处理不同的部分。
立即学习“Java免费学习笔记(深入);
优化代码如下:
public List<Map> createGroupTreeNode() { List<Map> childrenList = getChildList(0L); // ... } public List<Map> getChildList(Long id) { List<BaseGroup> childList = baseMapper.childListByParentId(id); if(childList != null && childList.size() > 0){ List<Map> tempMap = new ArrayList<Map>(); for (BaseGroup it : childList) { Map map = new HashMap(); map.put("id", it.getId()); map.put("text", it.getNumber() + " - " + it.getName()); map.put("icon", "fa fa-folder"); Map subMap = new HashMap(); subMap.put("opened", false); map.put("state", subMap); List<Map> mylist = getChildList(it.getId()); if (mylist == null) { map.put("isleaf", "1"); } else { map.put("isleaf", "0"); map.put("children", mylist); } tempMap.add(map); } return tempMap; } return null; }
通过这些修改,我们简化了代码,提高了代码的可读性和效率。
如何优化Java树结构递归生成效率低下?详情请关注图灵教育其他相关文章!
