public interface TreeNode {
String getId();
String getpId();
List getChildren();
}
public class TreeBuilder {
/**
* @param nodes 需要構建的nodes,不要繼承 TreeNode,且需要有 TreeNode 下的三個方法
* @param pId 父id。為null則是所有pid為null的是頂級節點;不為null,則是從給的pId往下查詢並構建樹
**/
public static <T extends TreeNode> List<T> buildTree(List<T> nodes, String pId) {
List<T> roots = new ArrayList<>();
for (T node : nodes) {
if (node.getId().equals(pId) || (node.getParentId() == null && (pId == null || pId.equals(node.getId())))) {
roots.add(node);
}
}
for (T root : roots) {
buildChildren(root, nodes);
}
return roots;
}
private static <T extends TreeNode> void buildChildren(T node, List<T> nodes) {
for (T child : nodes) {
if (child.getParentId() != null && child.getParentId().equals(node.getId())) {
node.getChildren().add(child);
buildChildren(child, nodes);
}
}
}
}
public class TreeBuilder {
/**
* @param level 級別 從1開始。1是最頂層
**/
public static <T extends TreeNode> List<T> buildTree(List<T> nodes, String pId, int level) {
List<T> roots = new ArrayList<>();
for (T node : nodes) {
if (node.getId().equals(pId) || (node.getParentId() == null && (pId == null || pId.equals(node.getId())))) {
roots.add(node);
}
}
for (T root : roots) {
buildChildren(root, nodes, level, 1);
}
return roots;
}
private static <T extends TreeNode> void buildChildren(T node, List<T> nodes, int level, int currentLevel) {
if (currentLevel >= level) {
return;
}
for (T child : nodes) {
if (child.getParentId() != null && child.getParentId().equals(node.getId())) {
if (node.getChildren() == null) {
node.setChildren(new ArrayList<>());
}
node.getChildren().add(child);
buildChildren(child, nodes, level, currentLevel + 1);
}
}
}
}
public class MyTreeVo implements TreeNode {
/**
* 主鍵
*/
private String id;
/**
* 父節點ID
*/
private String pId;
/**
* 子級
*/
private List<MyTreeVo> children = Lists.newArrayList();
//其他屬性……
public List<MyTreeVo> getChildren() {
return children;
}
public String getId() {
return id;
}
public String getpId() {
return pId;
}
//其他屬性的getter、setter……
-- pId可以傳入null,也可以傳入需要從哪個節點(X)開始構造的 X的id
-- pId比如可以傳入3、樣例中的 「二、噢噢噢噢」的id=「e6ee51485389495cb923a122be800012」。然後構建出來的,就是「二、噢噢噢噢」的下級樹
List<MyTreeVo> tree = TreeUtilQz.buildTree(vos,null);
//tree就是構建好的樹結構資料
{
"data": [
{
"id": "e6ee51485389495cb923a122be800011",
"pId": "",
"name": "一、鋼管鋼管",
"children": [
{
"id": "e6ee51485389495cb923a122be800014",
"pId": "e6ee51485389495cb923a122be800011",
"name": "(二)嘎嘎嘎嘎嘎",
"children": []
},
{
"id": "e6ee51485389495cb923a122be800013",
"pId": "e6ee51485389495cb923a122be800011",
"name": "(一)頂頂頂頂",
"children": []
}
]
},
{
"id": "e6ee51485389495cb923a122be800012",
"pId": "",
"name": "二、噢噢噢噢",
"children": [
{
"id": "e6ee51485389495cb923a122be800015",
"pId": "e6ee51485389495cb923a122be800012",
"name": "二的下級",
"children": [
{
"id": "e6ee51485389495cb923a122be800016",
"pId": "e6ee51485389495cb923a122be800015",
"name": "二的下級的下級",
"children": []
}
]
}
]
}
]
}