package com.cbb.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Component;
/**
*@Data
*@NoArgsConstructor
*@AllArgsConstructor
*@TableName("item")
* public class Item {
* @TableId(value = "eid", type = IdType.AUTO)
* private Integer eid;
* @TableField("name")
* private String name;
* @TableField("parent_id")
* private Integer parentId;
* @TableField(exist = false)
* private List<Item> chirldren;
*}
* @author 陈斌斌
* @Date 2022年9月11日 15点44分
*
*/
@Component
public class Tree {
/**
* 构建前端所需要树结构
*
* @param trees 列表
* @return 树结构列表
*/
public static List<Item> buildDeptTree(List<Item> trees) {
List<Item> returnList = new ArrayList<Item>();
List<Integer> tempList = new ArrayList<Integer>();
for (Item dept : trees) {
tempList.add(dept.getEid());
}
for (Iterator<Item> iterator = trees.iterator(); iterator.hasNext();) {
Item Item = (Item) iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(Item.getParentId())) {
recursionFn(trees, Item);
returnList.add(Item);
}
}
if (returnList.isEmpty()) {
returnList = trees;
}
return returnList;
}
/**
* 递归列表
*/
private static void recursionFn(List<Item> list, Item t) {
// 得到子节点列表
List<Item> childList = getChildList(list, t);
t.setChirldren(childList);
for (Item tChild : childList) {
if (hasChild(list, tChild)) {
recursionFn(list, tChild);
}
}
}
/**
* 得到子节点列表
*/
private static List<Item> getChildList(List<Item> list, Item t) {
List<Item> tlist = new ArrayList<Item>();
for (Item n : list) {
if (n.getParentId() != null && n.getParentId().longValue() == t.getEid().longValue()) {
tlist.add(n);
}
}
return tlist;
}
/**
* 判断是否有子节点
*/
private static boolean hasChild(List<Item> list, Item t) {
return getChildList(list, t).size() > 0;
}
}