1.直接上代码
public class CategoryVO {
/**
* id
*/
private Integer categoryId;
/**
* 节点名称
*/
private String categoryName;
/**
* 父id, 第一级父id为0
*/
private Integer parentId;
private List<CategoryVO> children = new LinkedList<>();
public CategoryVO(Integer categoryId, String categoryName, Integer parentId) {
this.categoryId = categoryId;
this.categoryName = categoryName;
this.parentId = parentId;
}
public static void main(String[] args) {
final List<CategoryVO> categories = Arrays.asList(
new CategoryVO(1, "根节点1", 0),
new CategoryVO(2, "根节点2", 0),
new CategoryVO(3, "根节点3", 0),
new CategoryVO(4, "子节点1,4", 1),
new CategoryVO(5, "子节点1,5", 1),
new CategoryVO(6, "子节点2,6", 2),
new CategoryVO(7, "子节点1,5,7", 5)
);
final Map<Integer, CategoryVO> categoryIdMap =
categories.stream()
.collect(Collectors
.toMap(CategoryVO::getCategoryId, Function.identity()));
final List<CategoryVO> tree = categories.stream()
.peek(category -> {
final Integer parentId = category.getParentId();
final CategoryVO categoryVO = categoryIdMap.get(parentId);
if (Objects.nonNull(categoryVO)) {
// 子节点自己去找父亲, 找到了挂在父亲下面, 然后取父节点就行了
categoryVO.getChildren().add(category);
}
})
.filter(category -> category.getParentId() == 0)
.collect(Collectors.toList());
System.out.println(JSON.toJSONString(tree));
}
}
2.JSON结果打印
[
{
"categoryId":1,
"categoryName":"根节点1",
"children":[
{
"categoryId":4,
"categoryName":"子节点1,4",
"children":[
],
"parentId":1
},
{
"categoryId":5,
"categoryName":"子节点1,5",
"children":[
{
"categoryId":7,
"categoryName":"子节点1,5,7",
"children":[
],
"parentId":5
}
],
"parentId":1
}
],
"parentId":0
},
{
"categoryId":2,
"categoryName":"根节点2",
"children":[
{
"categoryId":6,
"categoryName":"子节点2,6",
"children":[
],
"parentId":2
}
],
"parentId":0
},
{
"categoryId":3,
"categoryName":"根节点3",
"children":[
],
"parentId":0
}
]