树形结构的工具类
TreeUtils 类
package com.cloud.wl.hp.base.dto.tree;
import org.apache.commons.compress.utils.Lists;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class TreeUtils {
public static <T extends TreeNode<?>> List<T> generateTrees(List<T> nodes) {
List<T> roots = Lists.newArrayList();
for (Iterator<T> item = nodes.iterator(); item.hasNext(); ) {
T node = item.next();
if (node.root()) {
roots.add(node);
item.remove();
}
}
roots.forEach(e -> setChildren(e, nodes));
return roots;
}
public static <T extends TreeNode> void setChildren(T parent, List<T> nodes) {
List<T> children = Lists.newArrayList();
Object parentId = parent.id();
for (Iterator<T> iterator = nodes.iterator(); iterator.hasNext(); ) {
T node = iterator.next();
if (Objects.equals(node.parentId(), parentId)) {
children.add(node);
iterator.remove();
}
}
if (children.isEmpty()) {
return;
}
parent.setChildren(children);
children.forEach(e -> setChildren(e, nodes));
}
public static <T extends TreeNode<?>> List<T> getLeaves(T parent) {
List<T> leaves = Lists.newArrayList();
fillLeaf(parent, leaves);
return leaves;
}
private static <T extends TreeNode> void fillLeaf(T parent, List<T> leaves) {
}
}
TreeNode 类
package com.cloud.wl.hp.base.dto.tree;
import java.util.List;
public interface TreeNode<T> {
T id();
T parentId();
Boolean root();
void setChildren(List<? extends TreeNode<T>> children);
List<? extends TreeNode<T>> getChildren();
}
|