本文原创: https://blog.csdn.net/u011625492/article/details/78459287
业务场景: 管理系统登陆后,需要将菜单按照树形结构来显示.如下所示
代码实现
package com.cn.cs.util; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.cn.cs.model.SiteResource; public class TreeUtil { private List<SiteResource> nodes; public TreeUtil(List<SiteResource> nodes) { this.nodes=nodes; } /** * 创建树 * @return */ public List<TreeMessage> buildTree(){ List<TreeMessage> list = new ArrayList<TreeMessage>();
//获取最顶级菜单 for (SiteResource node : nodes) { if(node.getNodeCode().length()==2) { TreeMessage tm = new TreeMessage(); tm.setId(Integer.parseInt(node.getId())); tm.setNodeIndex(Integer.parseInt(node.getNodeIndex().toString())); tm.setNodeCode(node.getNodeCode()); tm.setText(node.getName()); tm.setChecked(true); list.add(tm); } } list = getSortChildren(list); for (TreeMessage node : list) { build(node); } return list; } /** * 构建权限树
* 获取菜单中的所有子菜单,并添加到父菜单中 */ private void build(TreeMessage node){ List<TreeMessage> children = getChildren(node); if (!children.isEmpty()) { node.setChildren(children); for (TreeMessage child : children) { build(child); } } } /* * * @Description: TODO 获取子节点 * @return */ private List<TreeMessage> getChildren(TreeMessage node){ List<TreeMessage> children = new ArrayList<TreeMessage>(); String nodeCode = node.getNodeCode(); for (SiteResource child : nodes) { if (nodeCode.equals(child.getPcode())) { TreeMessage tm = new TreeMessage(); tm.setId(Integer.parseInt(child.getId())); tm.setNodeCode(child.getNodeCode()); tm.setNodeIndex(Integer.parseInt(child.getNodeIndex().toString())); tm.setText(child.getName()); tm.setChecked(true); Attributes attributes = new Attributes(); attributes.setUrl(child.getUrl()); tm.setAttributes(attributes); children.add(tm); } } return getSortChildren(children); } /* * * * @Title: getChildren * @Description: TODO 获取排序子节点 * @param node * @return */ private List<TreeMessage> getSortChildren(List<TreeMessage> children){ ComparatorResource my = new ComparatorResource(); //这是一个自定义比较器,按照下标顺序排序 Collections.sort(children,my) ; return children; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步