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

org.macrocloud.kernel.toolkit.node.ForestNodeManager Maven / Gradle / Ivy

There is a newer version: 1.1.0-RELEASE
Show newest version
package org.macrocloud.kernel.toolkit.node;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.macrocloud.kernel.toolkit.utils.StringPool;

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


/**
 * 森林管理类.
 *
 * @author macro
 */
public class ForestNodeManager> {

	/** 森林的所有节点. */
	private final ImmutableMap nodeMap;

	/** 森林的父节点ID. */
	private final Map parentIdMap = Maps.newHashMap();

	/**
	 * Instantiates a new forest node manager.
	 *
	 * @param nodes the nodes
	 */
	public ForestNodeManager(List nodes) {
		nodeMap = Maps.uniqueIndex(nodes, INode::getId);
	}

	/**
	 * 根据节点ID获取一个节点.
	 *
	 * @param id 节点ID
	 * @return INode 对应的节点对象
	 */
	public INode getTreeNodeAt(Long id) {
		if (nodeMap.containsKey(id)) {
			return nodeMap.get(id);
		}
		return null;
	}

	/**
	 * 增加父节点ID.
	 *
	 * @param parentId 父节点ID
	 */
	public void addParentId(Long parentId) {
		parentIdMap.put(parentId, StringPool.EMPTY);
	}

	/**
	 * 获取树的根节点(一个森林对应多颗树).
	 *
	 * @return List 树的根节点集合
	 */
	public List getRoot() {
		List roots = new ArrayList<>();
		nodeMap.forEach((key, node) -> {
			if (node.getParentId() == 0 || parentIdMap.containsKey(node.getId())) {
				roots.add(node);
			}
		});
		return roots;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy