package com.yqzx.common.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 <T> List<Map> convert2Tree(List<T> list) {
|
return convert2Tree(list, null, "children");
|
}
|
|
public static <T> List<Map> convert2Tree(List<T> list, String childrenKey) {
|
return convert2Tree(list, null, childrenKey);
|
}
|
|
public static <T> List<Map> convert2Tree(List<T> list, Map<String, String> 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<java.util.Map>
|
* @author ChenLong
|
* @date 2019/4/23 18:44
|
* @version 1.0
|
*/
|
public static <T> List<Map> convert2Tree(List<T> list, Map<String, String> mapping, String childrenKey) {
|
if (list == null || list.size() <= 0) {
|
return new ArrayList<Map>();
|
}
|
|
Map root = new HashMap();
|
root.put(childrenKey, new ArrayList<Map>());
|
|
LinkedHashMap<String, Map> dataSet = new LinkedHashMap<String, Map>();
|
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()) {
|
String pid = Convert.toStr((((Map) dataSet.get(key)).get("pid")));
|
if (pid.equals("0")) {
|
((List<Map>) 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<Map>();
|
pNode.put(childrenKey, children);
|
}
|
((List<Map>) pNode.get(childrenKey)).add((Map) dataSet.get(key));
|
} else {
|
((List<Map>) root.get(childrenKey)).add((Map) dataSet.get(key));
|
}
|
}
|
}
|
|
if (root.get(childrenKey) != null) {
|
return (List<Map>) root.get(childrenKey);
|
} else {
|
return new ArrayList<Map>();
|
}
|
|
}
|
|
}
|