java实现tree树形结构

java实现tree树形结构
public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
    List<T> trees = new ArrayList<T>();
    for (T treeNode : treeNodes) {
        if (root.equals(treeNode.getParentId())) {
            trees.add(findChildren(treeNode, treeNodes));
        }
    }
    return trees;
}

/**
 * 递归查找子节点
 *
 * @param treeNodes
 * @return
 */
public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
    for (T it : treeNodes) {
        if (treeNode.getId() == it.getParentId()) {
            if (treeNode.getChildren() == null) {
                treeNode.setChildren(new ArrayList<>());
            }
            treeNode.add(findChildren(it, treeNodes));
        }
    }
    return treeNode;
}

 /**
  * 两层循环实现建树
  *
  * @param treeNodes 传入的树节点列表
  * @return
  */
 public <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {

     List<T> trees = new ArrayList<>();

     for (T treeNode : treeNodes) {

         if (root.equals(treeNode.getParentId())) {
             trees.add(treeNode);
         }

         for (T it : treeNodes) {
             if (it.getParentId() == treeNode.getId()) {
                 if (treeNode.getChildren() == null) {
                     treeNode.setChildren(new ArrayList<>());
                 }
                 treeNode.add(it);
             }
         }
     }
     return trees;
 }

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18463

发表评论