由于工作中好多地方需要树状结构数据,在参考了网上递归实现和数据库存储过程实现,都不太满意。突然想到zTree也有解析该类数据的要求,所以在阅读了zTree源码的前提了,按照他的实现原理,写了一个java版的实现方案
@SuppressWarnings("unchecked")public List<Map<String, Object>> parseTree(List<Map<String, Object>> list) {List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();Map<String, Object> tmpMap = new HashMap<String, Object>();for (int i = 0, l = list.size(); i < l; i++) {tmpMap.put(String.valueOf(list.get(i).get("id")), list.get(i));}for (int i = 0, l = list.size(); i < l; i++) {Map<String, Object> map = list.get(i);//tmpMap存储的均为id为key的键值对,如果以pid为key可以取出对象,则表明该元素是父级元素if(tmpMap.get(map.get("pid")) != null && (map.get("id") != map.get("pid"))){//给当前这个父级map对象中添加key为children的ArrayListif ((tmpMap.get(map.get("pid")) != null) && ((Map<String, Object>) tmpMap.get(map.get("pid"))).get("children") == null) {((Map<String,Object>) tmpMap.get(map.get("pid"))).put("children", new ArrayList<Map<String, Object>>());}Map<String, Object> tmap = (Map<String, Object>) tmpMap.get(map.get("pid"));ArrayList<Map<String, Object>> tArrayList = (ArrayList<Map<String, Object>>) tmap.get("children");tArrayList.add(list.get(i));//没有父节点} else {resultList.add(list.get(i));}}for (int i = 0, l = list.size(); i < l; i++) {System.out.println("原始数据是否变化:" + list.get(i));}Iterator<Entry<String, Object>> iterator = tmpMap.entrySet().iterator();while (iterator.hasNext()) {Entry<String, Object> entry = iterator.next();System.out.println("遍历之后:" + entry.getKey() + ":" + entry.getValue());}return resultList;}
数据库中的测试数据
解析完成后树状结构如下
如果觉得《Java - 树状结构数据解析》对你有帮助,请点赞、收藏,并留下你的观点哦!