zoukankan      html  css  js  c++  java
  • 记一个递归封装树形结构

    最近改了个小bug,原有的数据字典查询,封装成树的递归写的有问题,就自己写了一个,解决这种递归的思考是:分析树形结构-->>找到父子层之间的关联关系-->>根据关系编写递归嵌套条件。代码很简单也很实用,遂总结如下

    表结构

    截取表结构如下,关联id 和pid(父id).其中树最外层pid为0

    代码逻辑

    public List<Map<String, Object>> getRootDict() {
    	List<Map<String, Object>> returnList = new ArrayList<>();
    	// 查询所有数据字典
    	List<Map<String, Object>> dictList = dictMapper.getAllDict();
    	Map<String, Object> map = new HashMap<>(16);
    	map.put("name", "数据字典");
    	map.put("id", null);
    	map.put("pid", null);
    	
    	// 构建树形结构
    	List<Map<String, Object>> rootTree = this.rebuildRootTree("0",dictList);
    	map.put("child", rootTree);
    	returnList.add(map);
    	return returnList;
    }
    
    /**
     * 构建树结构
     * @param pid
     * @param dictList
     * @return
     */
    List<Map<String, Object>> rebuildRootTree(String pid ,List<Map<String, Object>> dictList){
    	List<Map<String, Object>> rootTree = new ArrayList<>();
    	for(Map<String, Object> dictMap:dictList){
    		if(dictMap.containsKey("pid") && Objects.equals(dictMap.get("pid").toString(),pid)) {
    			Map<String, Object> newMap = new HashMap<>(16);
    			newMap.put("name", dictMap.get("name"));
    			newMap.put("id", dictMap.get("id"));
    			newMap.put("pid", dictMap.get("pid"));
    			//递归调用
    			newMap.put("child",this.rebuildRootTree((dictMap.get("id")).toString(),dictList));
    			rootTree.add(newMap);
    		}
    	}
    	return rootTree;
    }
    

    若为实体,替换为对应的实体类即可;好了,就酱!日常生活的小技巧,还是总结下

    余路那么长,还是得带着虔诚上路...
  • 相关阅读:
    .Net连接字符串设置连接池大小显著提高数据库速度
    转载:MongoDB之旅(超赞,适合初学者)
    MongoDB安装成为Windows服务及日常使用遇到问题总结
    开启Windows文件共享必须开启的两个服务
    Cocos2d-JS中瓦片地图API
    EF-CodeFirst 继承关系TPH、TPT、TPC
    MVC5-4 ViewResult
    MVC5-3 Result分析
    MVC5-2 MVC的管道流与路由
    MVC5-1 ASP.NET的管道流
  • 原文地址:https://www.cnblogs.com/itiaotiao/p/13372229.html
Copyright © 2011-2022 走看看