1.TreeNode类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TreeNode {
Integer id;
String value;
/** 子节点信息 */
List<TreeNode> childrens;
/** 父节点信息,根节点的父Id是0 */
Integer parentId;
public TreeNode(Integer id, String value, Integer parentId) {
this.id = id;
this.value = value;
this.parentId = parentId;
}
}
2.测试类
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class TreeNodeAssemble {
public static void main(String[] args) {
List<TreeNode> list = createList();
//根据parentId=0获取根节点
List<TreeNode> collect = list.stream().filter(m -> m.parentId == 0).map(
(x) -> {x.childrens = getChildren(x, list);
return x;
}
).collect(Collectors.toList());
JSON json = JSONUtil.parse(collect);
System.out.println(json);
}
/**
* 递归查询子节点
* @param root
* @param listAll
* @return
*/
private static List<TreeNode> getChildren(TreeNode root, List<TreeNode> listAll) {
List<TreeNode> children = listAll.stream().filter(x-> Objects.equals(x.parentId, root.id))
.map(y->{
y.childrens = getChildren(y,listAll);
return y;})
.collect(Collectors.toList());
return children;
}
private static List<TreeNode> createList() {
List<TreeNode> list = Arrays.asList(
new TreeNode(1,"跟节点",0),
new TreeNode(2,"韦德-狗1",1),
new TreeNode(3,"韦德-猪1",1),
new TreeNode(4,"韦德-狗1-2",2),
new TreeNode(5,"韦德-狗1-3",2),
new TreeNode(6,"韦德-猪1-2",3),
new TreeNode(7,"韦德-狗1-2-4",4),
new TreeNode(8,"韦德-狗1-2-5",4),
new TreeNode(9,"韦德-猪2-3",6),
new TreeNode(10,"韦德-猪2-4",6)
);
return list;
}
}
3.结果