类1:
import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.gson.Gson; /** * 树结构生成工具类 */ public class Tree<T> implements Serializable { private static final long serialVersionUID = 1345222496369964150L; public String level; public T data; public List<Tree<T>> children; // 建立code索引各节点指针池 @JsonIgnore private Map<String, Tree<T>> pool = new HashMap<String, Tree<T>>(); public Tree<T> get(String code) { return pool.get(code); } public Tree(T data){ this.data = data; children = new ArrayList<Tree<T>>(); } public Tree(T data, String level){ this.data = data; this.level = level; } public void addChild(Tree<T> child){ this.children.add(child); } /** * 转换为树结构 */ public static <T> List<Tree<T>> transform(List<T> datas, String codeField, String parentField) throws BusinessServiceException { return transform(datas, codeField, parentField, null); } public static <T> List<Tree<T>> transform(List<T> datas, String codeField, String parentField, String levelField) throws BusinessServiceException { try { if(CollectionUtils.isEmpty(datas)) { return null; } // 返回的根节点 List<Tree<T>> tree = new ArrayList<Tree<T>>(); // 建立code索引各节点指针池 Map<String, Tree<T>> pool = new HashMap<String, Tree<T>>(); for(T data : datas){ String id = String.valueOf(PropertyUtils.getProperty(data, codeField)); if(StringUtils.isBlank(id)) { continue; } if(pool.containsKey(id)){ throw new BusinessServiceException("ID重复!id="+id); } pool.put(id, new Tree<T>(data)); } // 链接父子关系 for(T data : datas){ String id = String.valueOf(PropertyUtils.getProperty(data, codeField)); if(StringUtils.isBlank(id)) { continue; } String parent = String.valueOf(PropertyUtils.getProperty(data, parentField)); // 查找是否存在父节点,如果存在,则插入到父节点后,否则保存为根节点 if(pool.containsKey(parent)){ // 插入到父节点后 pool.get(parent).addChild(pool.get(id)); } else { // 保存根节点 pool.get(id).pool = pool; tree.add(pool.get(id)); } } if(StringUtils.isBlank(levelField)) { // 解析层级 for(int i=0; i<tree.size(); i++) { Tree root = tree.get(i); root.setLevelBySort(null, i+1); } }else { // 解析组织层级链 for(Tree root : tree) { root.setLevelByCode(null, levelField); } } // 为树建立code索引各节点指针池 for(Tree root : tree) { root.createPool(codeField); } return tree; } catch (Exception e) { throw new BusinessServiceException("转换树结构失败!", e); } } /** * 将该类分父子层级,放到类中children字段中 * */ public static <T> List<T> transformT(List<T> datas, String codeField, String parentField) throws BusinessServiceException { try { if(CollectionUtils.isEmpty(datas)) { return null; } // 返回的根节点 List<T> tree = new ArrayList<T>(); // 建立code索引各节点指针池 Map<String, T> pool = new HashMap<String, T>(); for(T data : datas){ String id = String.valueOf(PropertyUtils.getProperty(data, codeField)); if(StringUtils.isBlank(id)) { continue; } if(pool.containsKey(id)){ throw new BusinessServiceException("ID重复!id="+id); } pool.put(id, data); } // 链接父子关系 for(T data : datas){ String id = String.valueOf(PropertyUtils.getProperty(data, codeField)); if(StringUtils.isBlank(id)) { continue; } String parent = String.valueOf(PropertyUtils.getProperty(data, parentField)); // 查找是否存在父节点,如果存在,则插入到父节点后,否则保存为根节点 if(pool.containsKey(parent)){ // 插入到父节点后 List<T> childrenList = (List<T>) PropertyUtils.getProperty(pool.get(parent), "children"); childrenList.add(data); } else { // 保存根节点 tree.add(pool.get(id)); } } return tree; } catch (Exception e) { throw new BusinessServiceException("转换树结构失败!", e); } } /** * 从有父子关系的数据list中,获取某些编码的数据及其子数据 * * @param datas * @param codeField * @param parentField * @param codes 待过滤数据编码 * @return * @throws BusinessServiceException */ public static <T> List<T> filterListByTree(List<T> datas, String codeField, String parentField, String codes) throws BusinessServiceException { if(StringUtils.isBlank(codes) || CollectionUtils.isEmpty(datas)) { return datas; } // 过滤后数据 Set<T> filterSet = new HashSet<>(); // 过滤出来的数据树 List<Tree<T>> filterTree = new ArrayList<>(); // 需要过滤的数据编码 String[] codeArr = codes.split("[,;]"); // 当前所有数据树 List<Tree<T>> dataTree = Tree.transform(datas, codeField, parentField); for(String code : codeArr) { for(Tree<T> tree : dataTree) { // 过滤出的该编码的树 Tree<T> needTree = tree.get(code); if(needTree!=null) { // 加入过滤出来的数据树 filterTree.add(needTree); break; } } } // 树转化为list for(Tree<T> tree : filterTree) { filterSet.addAll(tree.toList()); } return new ArrayList<T>(filterSet); } public void setLevelBySort(String parentLevel, int sort) { this.level = StringUtils.isNotBlank(parentLevel) ? (parentLevel + "-" + sort) : String.valueOf(sort); if(!CollectionUtils.isEmpty(this.children)) { for(int i=0; i<this.children.size(); i++) { Tree childTree = this.children.get(i); childTree.setLevelBySort(this.level, i+1); } } } public void setLevelByCode(String parentLevel, String codeField) throws Exception { //分隔符 String splitTab = "-"; String code = String.valueOf(PropertyUtils.getProperty(this.data, codeField)); this.level = StringUtils.isNotBlank(parentLevel) ? (parentLevel + code + splitTab) : (code + splitTab); if(!CollectionUtils.isEmpty(this.children)) { for(Tree childTree : this.children) { childTree.setLevelByCode(this.level, codeField); } } } /** * 建立code索引各节点指针池 */ public Map<String, Tree<T>> createPool(String codeField) throws Exception { String code = String.valueOf(PropertyUtils.getProperty(this.data, codeField)); this.pool.put(code, this); if(!CollectionUtils.isEmpty(this.children)) { for(Tree childTree : this.children) { this.pool.putAll(childTree.createPool(codeField)); } } return this.pool; } /** * 转成列表 * */ public List<T> toList() { List<T> list = new ArrayList<T>(); list.add(this.data); if(!CollectionUtils.isEmpty(this.children)) { for(Tree childTree : this.children) { list.addAll(childTree.toList()); } } return list; } /** * 转成树列表 * */ public List<Tree<T>> toTreeList() { List<Tree<T>> list = new ArrayList<Tree<T>>(); list.add(new Tree(this.data, this.level)); if(!CollectionUtils.isEmpty(this.children)) { for(Tree childTree : this.children) { list.addAll(childTree.toTreeList()); } } return list; } /************************************** test **************************/ public class Node{ private String code; private String name; private String parentCode; public Node(String code, String name, String parentCode){ this.code = code; this.name = name; this.parentCode = parentCode; } public String getCode(){ return this.code; } public String getParentCode(){ return this.parentCode; } } public String test(){ List<Node> nodelist = new ArrayList<Node>(); nodelist.add(new Node("a", "i am a", "root")); nodelist.add(new Node("b", "i am b", "a")); nodelist.add(new Node("c", "i am c", "a")); nodelist.add(new Node("b1", "i am b1", "b")); nodelist.add(new Node("b11", "i am b11", "b1")); nodelist.add(new Node("c1", "i am c1", "c")); try { List<Tree<Node>> tree = transform(nodelist, "code", "parentCode"); Gson gson = new Gson(); String str = gson.toJson(tree); System.out.println(str); return str; } catch (Exception e) { e.printStackTrace(); return null; } } }
类2:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
/**
* 树结构生成工具类
*/
public class CheckTree implements Serializable {
private static final long serialVersionUID = 1345222696369964150L;
public String code;
public String title;
public String level;
public List<CheckTree> children;
public CheckTree(String code, String title){
children = new ArrayList<CheckTree>();
this.code = code;
this.title = title;
}
public void addChild(CheckTree child){
this.children.add(child);
}
/**
* 转换为树结构
*/
public static <T> List<CheckTree> transform(List<T> datas, String codeField, String parentField, String titleField) throws BusinessServiceException {
try {
// 返回的根节点
List<CheckTree> tree = new ArrayList<CheckTree>();
// 建立id索引各节点指针池
Map<String, CheckTree> pool = new HashMap<String, CheckTree>();
for(T data : datas){
String id = String.valueOf(PropertyUtils.getProperty(data, codeField));
String title = String.valueOf(PropertyUtils.getProperty(data, titleField));
if(pool.containsKey(id)){
throw new BusinessServiceException("ID重复!");
}
pool.put(id, new CheckTree(id, title));
}
// 链接父子关系
for(T data : datas){
String id = String.valueOf(PropertyUtils.getProperty(data, codeField));
String parent = String.valueOf(PropertyUtils.getProperty(data, parentField));
// 查找是否存在父节点,如果存在,则插入到父节点后,否则保存为根节点
if(pool.containsKey(parent)){
// 插入到父节点后
pool.get(parent).addChild(pool.get(id));
} else {
// 保存根节点
tree.add(pool.get(id));
}
}
// 解析层级
for(int i=0; i<tree.size(); i++) {
CheckTree root = tree.get(i);
root.setLevel(null, i+1);
}
return tree;
} catch (Exception e) {
throw new BusinessServiceException("转换树结构失败!", e);
}
}
public void setLevel(String level, int sort) {
this.level = StringUtils.isNotBlank(level) ? (level + "-" + sort) : String.valueOf(sort);
if(!CollectionUtils.isEmpty(this.children)) {
for(int i=0; i<this.children.size(); i++) {
CheckTree childTree = this.children.get(i);
childTree.setLevel(this.level, i+1);
}
}
}
/************************************** test **************************/
public class Node{
private String code;
private String name;
private String parentCode;
public Node(String code, String name, String parentCode){
this.code = code;
this.name = name;
this.parentCode = parentCode;
}
public String getCode(){
return this.code;
}
public String getParentCode(){
return this.parentCode;
}
}
public String test(){
List<Node> nodelist = new ArrayList<Node>();
nodelist.add(new Node("a", "i am a", "root"));
nodelist.add(new Node("b", "i am b", "a"));
nodelist.add(new Node("c", "i am c", "a"));
nodelist.add(new Node("b1", "i am b1", "b"));
nodelist.add(new Node("b11", "i am b11", "b1"));
nodelist.add(new Node("c1", "i am c1", "c"));
try {
List<CheckTree> tree = transform(nodelist, "code", "parentCode", "name");
Gson gson = new Gson();
String str = gson.toJson(tree);
System.out.println(str);
return str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
类3
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
/**
* 树结构生成工具类
*
*/
public class CheckTreeUtil implements Serializable {
private static final long serialVersionUID = 1345222696369964150L;
/****
* 转换为树结构
*
* @param datas
* @param paramsName
* map类型 key为最终要显示的字段名称 value为T对象中字段名称
* @param codeField
* code字段名称
* @param parentField
* 父节点code字段名称
* @return
* @throws BusinessServiceException
*/
public static <T> List<Map<String, Object>> transform(List<T> datas, Map<String, Object> paramsName,
String codeField, String parentField) throws BusinessServiceException {
try {
// 返回的根节点
List<Map<String, Object>> tree = new ArrayList<Map<String, Object>>();
// 建立id索引各节点指针池
Map<String, Map<String, Object>> pool = new HashMap<String, Map<String, Object>>();
for (T data : datas) {
Map<String, Object> objMap = new HashMap<>();
for (String key : paramsName.keySet()) {
objMap.put(key, String.valueOf(PropertyUtils.getProperty(data, paramsName.get(key).toString())));
}
String id = String.valueOf(PropertyUtils.getProperty(data, codeField));
if (pool.containsKey(id)) {
throw new BusinessServiceException("ID重复!");
}
pool.put(id, objMap);
}
// 链接父子关系
for (T data : datas) {
String id = String.valueOf(PropertyUtils.getProperty(data, codeField));
String parent = String.valueOf(PropertyUtils.getProperty(data, parentField));
// 查找是否存在父节点,如果存在,则插入到父节点后,否则保存为根节点
if (pool.containsKey(parent)) {
// 插入到父节点后
if (pool.get(parent).get("children") != null) {
((List<Map<String, Object>>) pool.get(parent).get("children")).add(pool.get(id));
} else {
List<Map<String, Object>> children = new ArrayList<>();
children.add(pool.get(id));
pool.get(parent).put("children", children);
}
} else {
// 保存根节点
tree.add(pool.get(id));
}
}
// 解析层级
for (int i = 0; i < tree.size(); i++) {
Map<String, Object> parent = tree.get(i);
CheckTreeUtil.setLevel(parent, null, i + 1);
}
return tree;
} catch (Exception e) {
throw new BusinessServiceException("转换树结构失败!", e);
}
}
public static void setLevel(Map<String, Object> parent, String level, int sort) {
String newLevel = StringUtils.isNotBlank(level) ? (level + "-" + sort) : String.valueOf(sort);
parent.put("level", newLevel);
if (parent.get("children") != null) {
List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
for (int i = 0; i < children.size(); i++) {
Map<String, Object> childTree = children.get(i);
CheckTreeUtil.setLevel(childTree, newLevel, i + 1);
}
}
}
/************************************** test **************************/
public class Node {
private String code;
private String name;
private String parentCode;
public Node(String code, String name, String parentCode) {
this.code = code;
this.name = name;
this.parentCode = parentCode;
}
public String getCode() {
return this.code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentCode() {
return this.parentCode;
}
}
public String test() {
List<Node> nodelist = new ArrayList<Node>();
nodelist.add(new Node("a", "i am a", "root"));
nodelist.add(new Node("b", "i am b", "a"));
nodelist.add(new Node("c", "i am c", "a"));
nodelist.add(new Node("b1", "i am b1", "b"));
nodelist.add(new Node("b11", "i am b11", "b1"));
nodelist.add(new Node("c1", "i am c1", "c"));
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("title", "name");
paramMap.put("code", "code");
paramMap.put("parentCode", "parentCode");
try {
List<Map<String, Object>> tree = transform(nodelist, paramMap, "code", "parentCode");
Gson gson = new Gson();
String str = gson.toJson(tree);
System.out.println(str);
return str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
CheckTreeUtil treeUtil = new CheckTreeUtil();
treeUtil.test();
}
// public void copyValuedProperties(Object source, Object target) throws Exception {
// for (Field field : source.getClass().getDeclaredFields()) {
// if ("serialVersionUID".equals(field.getName())) {
// continue;
// }
// boolean accessible = field.isAccessible();
// field.setAccessible(true);
// Object value = field.get(source);
// if (value == null || StringUtils.isBlank(value.toString())) {
// continue;
// }
// PropertyUtils.setProperty(target, field.getName(), value);
// field.setAccessible(accessible);
// }
// }
}