今天写了一个通用树构建方法,非常通用和简单,分享出来
基础类
@Data
public class Tree<T> {
String id;
String pId;
List<T> children;
}
测试类
@Data
public class TreeDemo extends Tree<TreeDemo> {
String name;
}
工具类
public class TreeUtils {
public static List buildTree(List<Tree> trees, String pId) {
for (Tree tree : trees) {
for (Tree tree1 : trees) {
if (tree1.getPId().equals(tree.getId())) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList());
}
tree.getChildren().add(tree1);
}
}
}
return trees.stream().filter(tree -> tree.getPId().equals(pId)).collect(Collectors.toList());
}
}
测试方法
public static void main(String[] args) {
List<TreeDemo> treeDemo = TreeUtils.buildTree(Arrays.asList(new TreeDemo(){{
setId("1");
setName("name");
setPId("-1");
}},new TreeDemo(){{
setId("2");
setName("name-1");
setPId("1");
}},new TreeDemo(){{
setId("3");
setName("name-2");
setPId("1");
}}),"-1");
System.out.println(treeDemo);
}