8000 feat: 查询通用 tree util · cadecode/uni-boot-cloud@2f7585b · GitHub
[go: up one dir, main page]

Skip to content

Commit 2f7585b

Browse files
committed
feat: 查询通用 tree util
1 parent 87dd2b1 commit 2f7585b

File tree

1 file changed

+47
-0
lines changed
  • common/core/src/main/java/com/github/cadecode/uniboot/common/core/util

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.github.cadecode.uniboot.common.core.util;
2+
3+
import cn.hutool.core.util.ObjUtil;
4+
5+
import java.util.List;
6+
import java.util.function.BiConsumer;
7+
import java.util.function.Function;
8+
import java.util.stream.Collectors;
9+
10+
/**
11+
* Tree 工具
12+
*
13+
* @author Cade Li
14+
* @since 2023/11/26
15+
*/
16+
public class TreeUtil {
17+
18+
/**
19+
* List 树形化
20+
*
21+
* @param list 原数据列表
22+
* @param rootId root id
23+
* @param idGetter 获取 id 的方法
24+
* @param parentIdGetter 获取 parentId 的方法
25+
* @param childrenSetter 设置 children 的方法
26+
* @return 树形化之后的列表
27+
* @param <T> 原数据类型
28+
* @param <L> 数据 ID 类型
29+
*/
30+
public static <T, L> List<T> listToTree(List<T> list,
31+
L rootId,
32+
Function<T, L> idGetter,
33+
Function<T, L> parentIdGetter,
34+
BiConsumer<T, List<T>> childrenSetter) {
35+
List<T> parentList = list.stream()
36+
.filter(o -> ObjUtil.equals(rootId, parentIdGetter.apply(o)))
37+
.collect(Collectors.toList());
38+
parentList.forEach(p -> {
39+
List<T> children = list.stream()
40+
.filter(c -> ObjUtil.equals(parentIdGetter.apply(c), idGetter.apply(p)))
41+
.peek(c -> childrenSetter.accept(c, listToTree(list, idGetter.apply(c), idGetter, parentIdGetter, childrenSetter)))
42+
.collect(Collectors.toList());
43+
childrenSetter.accept(p, children);
44+
});
45+
return parentList;
46+
}
47+
}

0 commit comments

Comments
 (0)
0