All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rivers.utils.tree.TreeUtil Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
package com.rivers.utils.tree;

import com.rivers.utils.dto.TreeNode;

import java.util.ArrayList;
import java.util.List;


/**
 * @author riversking
 */
public class TreeUtil {
	/**
	 * 两层循环实现建树
	 *
	 */
	public static  List bulid(List treeNodes, Object root) {

		List 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;
	}

	/**
	 * 使用递归方法建树
	 *
	 * @param treeNodes treeNodes
	 * @return
	 */
	public static  List buildByRecursive(List treeNodes, Object root) {
		List trees = new ArrayList<>();
		for (T treeNode : treeNodes) {
			if (root.equals(treeNode.getParentId())) {
				trees.add(findChildren(treeNode, treeNodes));
			}
		}
		return trees;
	}

	/**
	 * 递归查找子节点
	 *
	 * @param treeNodes treeNodes
	 * @return
	 */
	public static  T findChildren(T treeNode, List 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;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy