java web项目 树形菜单排序算法

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

猜你喜欢

转载自www.cnblogs.com/ldspeace/p/10965017.html