package com.nuvole.util; import cn.hutool.core.convert.Convert; import java.util.*; /** * @author ChenLong * @version 1.0 * @ClassName TreeUtil * @Description tree工具类 * @date 2019/4/23 15:50 */ public class TreeUtil { public static List convert2Tree(List list) { return convert2Tree(list, null, "children"); } public static List convert2Tree(List list, String childrenKey) { return convert2Tree(list, null, childrenKey); } public static List convert2Tree(List list, Map mapping) { return convert2Tree(list, mapping, "children"); } /** * 对象数组格式化为tree结构,对象中必须具有{id,pid}属性 * * @param list * @param mapping {"label":"name"} 将数据库查询list中的label属性替换为name属性 * @param childrenKey 自节点key名称 默认为children * @return : java.util.List * @author ChenLong * @date 2019/4/23 18:44 * @version 1.0 */ public static List convert2Tree(List list, Map mapping, String childrenKey) { if (list == null || list.size() <= 0) { return new ArrayList(); } Map root = new HashMap(); root.put(childrenKey, new ArrayList()); LinkedHashMap dataSet = new LinkedHashMap(); for (T obj : list) { Map map; if (obj instanceof Map) { map = new HashMap(){{ putAll((Map) obj); }}; } else { map = TypeConvertUtil.obj2Map(obj); } //结果转换 if (mapping != null) { for (String key : mapping.keySet()) { if (map.containsKey(key)) { map.put(mapping.get(key), map.get(key)); //移除原有属性 map.remove(key); } } } dataSet.put(Convert.toStr(map.get("id")), map); } //组装树 for (String key : dataSet.keySet()) { Object parentId = ((dataSet.get(key)).get("pid")); if(parentId == null){ /* 增加一种大小写类型 * @author dqh * @date 2024-04-12 **/ parentId = ((dataSet.get(key)).get("PId")); } String pid = Convert.toStr(parentId); if (pid.equals("0")) { ((List) root.get(childrenKey)).add((Map) dataSet.get(key)); } else { Map pNode = (Map) dataSet.get(pid); if (pNode != null) { if (pNode.get(childrenKey) == null) { List children = new ArrayList(); pNode.put(childrenKey, children); } ((List) pNode.get(childrenKey)).add((Map) dataSet.get(key)); } else { ((List) root.get(childrenKey)).add((Map) dataSet.get(key)); } } } if (root.get(childrenKey) != null) { return (List) root.get(childrenKey); } else { return new ArrayList(); } } }