Java 获取多级菜单目录

1.实体类封装 (get/set方法忽略)
private String planId;
private String projectId;
private String pId;
private String levelSort;
private String startTime;
private String endTime;
private String timeLength;
private String projectName;
private String age;
private  List childList = new ArrayList<>(); // 只要是装子节点的list(也可使用map)
2.具体的实现方式

@Override
public List selectPlan() {
    // 查询所有
    List list =  baseMapper.selectPlan();
        // 根节点
        List rootList = new ArrayList<>();
        for (ProjectPlanModel planModel : list) {
            // levelSort  为0 的是一级目录
            String levelSort = planModel.getLevelSort();
            if("0".equals(levelSort)){
                rootList.add(planModel);
            }
        }
        // 遍历父节点 获取子节点目录
        for (ProjectPlanModel planModel : rootList) {
            /* 获取根节点下的所有子节点 使用getChildList方法*/
            String projectId = planModel.getProjectId();
            List childList = getChildList(projectId,list);
            planModel.setChildList(childList);
        }

    return rootList;
}

/**
 *     获取子节点
 * @param projectId 父节点id
 * @param list 所有菜单列表
 * @return 每个根节点下,所有子菜单列表
 */
private List getChildList(String projectId, List list) {
    List childList = new ArrayList<>();
    for (ProjectPlanModel planModel : list) {
        // 遍历所有节点,将所有菜单的父id与传过来的根节点的id比较
        //相等说明:为该根节点的子节点。
        String pId = planModel.getpId();
        if(projectId.equals(pId)){
            childList.add(planModel);
        }
    }
    //递归
    for (ProjectPlanModel childModel : childList) {
        // 所谓的parentId(根据实际情况)
        String childProjectId = childModel.getProjectId();
        childModel.setChildList(getChildList(childProjectId,list));
    }
    //如果节点下没有子节点,返回一个空List(递归退出)
    if(childList.size()==0){
        return  new ArrayList<>();
    }
    return childList;
}

你可能感兴趣的:(笔记,java)