首页 > 代码库 > (原创)父子关系数据递归加工成tree形数据(减轻数据库压力)
(原创)父子关系数据递归加工成tree形数据(减轻数据库压力)
package test;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;/** * IdPIdDatasToTree<BR> * <P>Author : td </P> * <P>Date : 2016年9月30日下午4:54:59</P> * <P>Desc : 将上下级数据加工成为tree形数据结构</P> * @param response * @param request */public class IdPIdDatasToTree { public static void main(String[] args) { List < Map < String, Object >> list = new ArrayList < Map < String, Object >> (); Map < String, Object > m = null; for (int i = 1; i < 10; i++) { m = new HashMap < String, Object > (); m.put("id", i + ""); m.put("name", "我是节点" + i); m.put("parentId", i - 1 + ""); list.add(m); } List < Map < String, Object >> treeMenuList = new LinkedList < Map < String, Object >> (); treeMenuList = treeMenuList(list, treeMenuList, "0"); System.out.println("要加工的数据为:" + list.toString()); System.out.println("加工好的tree状结构为:" + treeMenuList.toString()); } /** * * @param menuList 原始数据 * @param treeMenuList tree数据对象 * @param parentId 数据的父id * @return */ @SuppressWarnings("unchecked") public static List < Map < String, Object >> treeMenuList(List < Map < String, Object >> list, List < Map < String, Object >> treeMenuList, String parentId) { //没有根节点情况下 if ("0".equals(parentId)) { treeMenuList = getChildNodeList("0", list); for (Map < String, Object > treeMenu: treeMenuList) { String id = (String) treeMenu.get("id"); treeMenu.put("childNode", getChildNodeList(id, list)); treeMenuList(list, treeMenuList, id); } } else { for (Map < String, Object > treeMenu: treeMenuList) { //判断是否有子元素,有的话递归子元素 继续判断 String id = (String) treeMenu.get("id"); if (treeMenu.containsKey("childNode")) { //获取子元素 List < Map < String, Object >> childNodeList = (List < Map < String, Object >> ) treeMenu.get("childNode"); if (childNodeList != null && childNodeList.size() > 0) { for (Map < String, Object > tMenu: childNodeList) { treeMenuList(list, childNodeList, tMenu.get("id").toString()); } } //如果没有子元素,根据id查询儿子 将儿子赋值 } else { List < Map < String, Object >> chList = getChildNodeList(id, list); if (null != chList) { treeMenu.put("childNode", chList); treeMenuList(list, chList, id); } } } } return treeMenuList; } /** * * @param parentId 数据父id * @param list 原始数据 * @return */ public static List < Map < String, Object >> getChildNodeList(String parentId, List < Map < String, Object >> list) { List < Map < String, Object >> childNodeList = new LinkedList < Map < String, Object >> (); for (Map < String, Object > childNode: list) { //从新new 对象 (如果不重新new对象,list 的值会随之变动,不知道咋回事?) Map < String, Object > m = new HashMap < String, Object > (); m.putAll(childNode); String pId = (String) childNode.get("parentId"); if (pId.equals(parentId)) { childNodeList.add(m); } } if (childNodeList.size() == 0) return null; return childNodeList; }}
(原创)父子关系数据递归加工成tree形数据(减轻数据库压力)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。