本文原創: 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; } }