树工具类,记录一下,以后备用。
1.Tree bean类,保存树节点信息
import java.util.ArrayList;
import java.util.List;
/**
* Created by rico on 2017/1/3.
* Tree bean
*/
public class TreeNode {
private E nodeId;
private E parentId;
private T data;
private List> children = new ArrayList>();
public TreeNode(E nodeId, E parentId, T data) {
this.nodeId = nodeId;
this.parentId = parentId;
this.data = data;
}
public E getNodeId() {
return nodeId;
}
public void setNodeId(E nodeId) {
this.nodeId = nodeId;
}
public E getParentId() {
return parentId;
}
public void setParentId(E parentId) {
this.parentId = parentId;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public List> getChildren() {
return children;
}
public void setChildren(List> children) {
this.children = children;
}
public void addChild(TreeNode node) {
children.add(node);
}
public boolean hasChildren() {
return (children!=null && !children.isEmpty());
}
}
2.树构建工具,递归遍历节点,构建树
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rico on 2017/1/3.
* 树构建工具
*/
public class TreeUtil {
private static final Logger logger = LoggerFactory.getLogger(TreeUtil.class);
public static TreeNode buildTree(List> nodes, E rootId) {
if(nodes==null || nodes.size()==0) {
return null;
}
// 查询根节点
TreeNode rootNode = getRootNode(nodes, rootId);
if(rootNode == null) {
logger.warn("未找到根节点rootId = {}", rootId);
return null;
}
// 遍历节点构造树
TreeNode treeNode = buildTree(nodes, rootNode);
return treeNode;
}
/**
* 遍历节点构造树
* @param nodes
* @param rootNode
* @param
* @param
* @return
*/
public static TreeNode buildTree(List> nodes, TreeNode rootNode) {
for(TreeNode node : nodes) {
if(node.getParentId().equals(rootNode.getNodeId())) {
// 子节点添加到父节点子集合
rootNode.addChild(node);
// 递归遍历子节点
buildTree(nodes, node);
}
}
return rootNode;
}
/**
* 查询根节点
* @param nodes
* @param rootId
* @param
* @param
* @return
*/
public static TreeNode getRootNode(List> nodes, E rootId) {
for(TreeNode node : nodes) {
//TODO 类型判断?
//if((rootId instanceof String) && rootId.equals(node.getRootId())) {
if(rootId.equals(node.getNodeId())) {
return node;
} else if(node.getNodeId() == rootId) {
return node;
}
}
return null;
}
/**
* 反转列表顺序
* @param list
* @param
* @return
*/
public static List reverseList(List list) {
if(list==null || list.isEmpty()) {
return list;
}
List temps = new ArrayList();
for(int i=list.size()-1; i>=0; i--) {
temps.add(list.get(i));
}
return temps;
}
/**
* 遍历数节点,转换为列表
* @param datas
* @param node
* @param include
* @param
* @param
* @return
*/
public static List toList(List datas, TreeNode node, boolean include) {
// 是否包含该节点
if(include) {
datas.add(node.getData());
}
if(!node.hasChildren()) {
return datas;
}
for(TreeNode subNode : node.getChildren()) {
toList(datas, subNode, true);
}
return datas;
}
}