/**
* 将 list 结构数据转成 tree 结构
*
* @param nodeList list 结构的数据
* @param isRootNodeCondition pid 为根节点的条件。eg. (t) -> t == 0
* @return List<Node>
*/
// public static List<Node> convertListToTreeNew(List<Node> nodeList, Predicate<Node> isRootNodeCondition) {
public static <T> List<T> convertListToTreeNew(List<T> nodeList,
Function<T, ?> idFun,
Function<T, ?> pidFun,
Function<T, List<T>> getChildFun,
BiConsumer<T, List<T>> setChildCon,
Predicate<T> isRootNodeCondition) {
// List<Node> treeList = new ArrayList<>();
List<T> treeList = new ArrayList<>();
// Map<Integer, Node> map = new ConcurrentHashMap<>();
Map<Object, T> map = new ConcurrentHashMap<>();
// 1 获取所有父节点
// for (Node node : nodeList) {
for (T node : nodeList) {
// if (node.getPId() == 0) {
if (isRootNodeCondition.test(node)) {
treeList.add(node);
}
// map.put(node.getId(), node);
map.put(idFun.apply(node), node);
}
log.info("获取所有父节点 treeList:[{}]", JsonUtil.toJson(treeList));
// 2 获取某个节点的父节点,然后将其添加到其父节点的子节点列表中
// for (Node node : nodeList) {
for (T node : nodeList) {
// final Node pNode = map.get(node.getPId());
final T pNode = map.get(pidFun.apply(node));
if (pNode != null) {
// final List<Node> childList = pNode.getChild();
final List<T> childList = getChildFun.apply(pNode);
if (childList == null) {
// pNode.setChild(new ArrayList<>());
setChildCon.accept(pNode, new ArrayList<>());
}
// pNode.getChild().add(node);
getChildFun.apply(pNode).add(node);
}
// final List<Node> child = node.getChild();
final List<T> child = getChildFun.apply(node);
if (child == null) {
// node.setChild(new ArrayList<>());
setChildCon.accept(node, new ArrayList<>());
}
}
log.info("组装完成的 tree 结构:[{}]", JsonUtil.toJson(treeList));
return treeList;
}
list转tree
于 2022-09-07 07:09:43 首次发布