package com.hkinfo.support.utils;
import org.apache.poi.ss.formula.functions.T;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TreeUtils<T, K> {
private final List<T> list;
private final Function<? super T, ? extends K> idFunc;
private final Function<? super T, ? extends K> pidFunc;
private final TreeChildConsumer<T> setChildren;
public TreeUtils(List<T> list,
Function<? super T, ? extends K> idFunc,
Function<? super T, ? extends K> pidFunc,
TreeChildConsumer<T> setChildren) {
this.list = list;
this.idFunc = idFunc;
this.pidFunc = pidFunc;
this.setChildren = setChildren;
}
public List<T> build() {
List<T> data = this.list;
if (data.isEmpty()) {
return null;
}
List<T> rootList = new ArrayList<>();
for (T root : data) {
if (data.stream().noneMatch(item -> idFunc.apply(item).equals(pidFunc.apply(root)))) {
rootList.add(buildChild(root));
}
}
return rootList;
}
protected T buildChild(T parent) {
List<T> children = new ArrayList<>();
for (T t : list) {
if (idFunc.apply(parent).equals(pidFunc.apply(t))) {
children.add(buildChild(t));
}
}
setChildren.accept(parent, children);
return parent;
}
@FunctionalInterface
public interface TreeChildConsumer<T> {
void accept(T t, List<T> tList);
}
}
使用方法
TreeUtils<RuleDict, String> tree = new TreeUtils<>(list, RuleDict::getId, RuleDict::getParentId, RuleDict::setChildren);
tree.build();