个人常用工具类:JAVA树形结构工具类02

Posted jiang4yu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了个人常用工具类:JAVA树形结构工具类02相关的知识,希望对你有一定的参考价值。

JAVA树形结构工具类02

TreeNode

import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by Ace on 2017/6/12.
 */
public class TreeNode 
    protected int id;
    protected int parentId;
    List<TreeNode> children = new ArrayList<TreeNode>();
 
    public List<TreeNode> getChildren() 
        return children;
    
 
    public void setChildren(List<TreeNode> children) 
        this.children = children;
    
    public int getId() 
        return id;
    
 
    public void setId(int id) 
        this.id = id;
    
 
    public int getParentId() 
        return parentId;
    
 
    public void setParentId(int parentId) 
        this.parentId = parentId;
    
 
    public void add(TreeNode node)
        children.add(node);
    

TreeUtil

import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by Ace on 2017/6/12.
 */
public class TreeUtil
  /**
   * 两层循环实现建树
   * 
   * @param treeNodes 传入的树节点列表
   * @return
   */
  public static <T extends TreeNode> List<T> bulid(List<T> treeNodes,Object root) 
 
    List<T> trees = new ArrayList<T>();
 
    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>());
          
          treeNode.add(it);
        
      
    
    return trees;
  
 
  /**
   * 使用递归方法建树
   * 
   * @param treeNodes
   * @return
   */
  public static <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 static <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>());
        
        treeNode.add(findChildren(it, treeNodes));
      
    
    return treeNode;
  
 

以上是关于个人常用工具类:JAVA树形结构工具类02的主要内容,如果未能解决你的问题,请参考以下文章

java 处理树形结构工具类

java 树形结构工具类

Java解析省市县树形结构工具类

组织机构列表转树形结构Hutool工具类TreeUtil

组织机构列表转树形结构Hutool工具类TreeUtil

java糊涂工具类是个人的吗