2018-12-24 11:58:45 +08:00
|
|
|
/**
|
|
|
|
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
|
|
|
|
* <p>
|
|
|
|
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE;
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
* <p>
|
|
|
|
* http://www.gnu.org/licenses/lgpl.html
|
|
|
|
* <p>
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
2018-12-25 21:43:17 +08:00
|
|
|
package org.springblade.core.tool.node;
|
2018-12-24 11:58:45 +08:00
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 森林管理类
|
|
|
|
*
|
2018-12-27 13:29:11 +08:00
|
|
|
* @author smallchill
|
2018-12-24 11:58:45 +08:00
|
|
|
*/
|
2018-12-27 11:29:51 +08:00
|
|
|
public class ForestNodeManager<T extends INode> {
|
2018-12-24 11:58:45 +08:00
|
|
|
|
2018-12-27 11:29:51 +08:00
|
|
|
/**
|
|
|
|
* 森林的所有节点
|
|
|
|
*/
|
|
|
|
private List<T> list;
|
2018-12-24 11:58:45 +08:00
|
|
|
|
2018-12-28 21:52:54 +08:00
|
|
|
/**
|
|
|
|
* 森林的父节点ID
|
|
|
|
*/
|
|
|
|
private List<Integer> parentIds = new ArrayList<>();
|
|
|
|
|
2018-12-27 11:29:51 +08:00
|
|
|
public ForestNodeManager(List<T> items) {
|
|
|
|
list = items;
|
|
|
|
}
|
2018-12-24 11:58:45 +08:00
|
|
|
|
2018-12-27 11:29:51 +08:00
|
|
|
/**
|
|
|
|
* 根据节点ID获取一个节点
|
|
|
|
*
|
|
|
|
* @param id 节点ID
|
|
|
|
* @return 对应的节点对象
|
|
|
|
*/
|
|
|
|
public INode getTreeNodeAT(int id) {
|
|
|
|
for (INode forestNode : list) {
|
|
|
|
if (forestNode.getId() == id) {
|
|
|
|
return forestNode;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
2018-12-24 11:58:45 +08:00
|
|
|
|
2018-12-28 21:52:54 +08:00
|
|
|
/**
|
|
|
|
* 增加父节点ID
|
|
|
|
*
|
2018-12-29 14:20:27 +08:00
|
|
|
* @param parentId 父节点ID
|
2018-12-28 21:52:54 +08:00
|
|
|
*/
|
|
|
|
public void addParentId(Integer parentId) {
|
|
|
|
parentIds.add(parentId);
|
|
|
|
}
|
|
|
|
|
2018-12-27 11:29:51 +08:00
|
|
|
/**
|
|
|
|
* 获取树的根节点(一个森林对应多颗树)
|
|
|
|
*
|
|
|
|
* @return 树的根节点集合
|
|
|
|
*/
|
|
|
|
public List<T> getRoot() {
|
|
|
|
List<T> roots = new ArrayList<>();
|
|
|
|
for (T forestNode : list) {
|
2018-12-28 21:52:54 +08:00
|
|
|
if (forestNode.getParentId() == 0 || parentIds.contains(forestNode.getId())) {
|
2018-12-27 11:29:51 +08:00
|
|
|
roots.add(forestNode);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return roots;
|
|
|
|
}
|
2018-12-24 11:58:45 +08:00
|
|
|
|
|
|
|
}
|