cn.renlm.plugins.MyUtil.MyTreeUtil Maven / Gradle / Ivy
/*
* Copyright (c) 2020 Renlm
* MyUtil is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package cn.renlm.plugins.MyUtil;
import java.util.List;
import java.util.function.Consumer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import lombok.experimental.UtilityClass;
/**
* 树工具类(扩展)
*
* @author RenLiMing(任黎明)
*
*/
@UtilityClass
public class MyTreeUtil extends TreeUtil {
/**
* 遍历树
*
* @param
* @param tree
* @param node
*/
public static final void foreach(List> tree, Consumer> node) {
if (CollUtil.isEmpty(tree)) {
return;
}
for (Tree item : tree) {
node.accept(item);
if (CollUtil.isNotEmpty(item.getChildren())) {
foreach(item.getChildren(), node);
}
}
}
/**
* 重设层级
*
* @param
* @param tree
* @param level
* @return
*/
public static final List> resetLevel(List> tree, int level) {
if (CollUtil.isEmpty(tree)) {
return CollUtil.newArrayList();
}
for (Tree node : tree) {
node.putExtra("level", level);
if (CollUtil.isNotEmpty(node.getChildren())) {
resetLevel(node.getChildren(), level + 1);
}
}
return tree;
}
/**
* 获取全部节点
*
* @param
* @param tree
* @return
*/
public static final List> getAllNodes(List> tree) {
List> nodes = CollUtil.newArrayList();
if (CollUtil.isEmpty(tree)) {
return nodes;
}
for (Tree node : tree) {
nodes.add(node);
if (CollUtil.isNotEmpty(node.getChildren())) {
nodes.addAll(getAllNodes(node.getChildren()));
}
}
return nodes;
}
}