我直接上代码
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RecDemoVO {
private Long id;
private String name;
private Long parentId;
private List<RecDemoVO> children;
}
public List<RecDemoVO> demo() {
List<RecDemoVO> list = createRecDemoVOData();
Map<Long, List<RecDemoVO>> parentIdToChildrenMap = list.stream()
.collect(Collectors.groupingBy(RecDemoVO::getParentId));
List<RecDemoVO> treeList = new ArrayList<>();
List<RecDemoVO> topLevelNodes = parentIdToChildrenMap.get(0L);
for (RecDemoVO topLevelNode : topLevelNodes) {
buildChildren(topLevelNode, parentIdToChildrenMap);
treeList.add(topLevelNode);
}
return treeList;
}
private void buildChildren(RecDemoVO parentNode, Map<Long, List<RecDemoVO>> parentIdToChildrenMap) {
List<RecDemoVO> list = parentIdToChildrenMap.get(parentNode.getId());
if (CollUtil.isEmpty(list)) {
return;
}
for (RecDemoVO recDemoVO : list) {
List<RecDemoVO> children = parentNode.getChildren();
if (children == null) {
children = new ArrayList<>();
children.add(recDemoVO);
parentNode.setChildren(children);
} else {
children.add(recDemoVO);
}
buildChildren(recDemoVO, parentIdToChildrenMap);
}
}
private List<RecDemoVO> createRecDemoVOData() {
List<RecDemoVO> list = new ArrayList<>();
list.add(RecDemoVO.builder().id(1L).name("1").parentId(0L).build());
list.add(RecDemoVO.builder().id(2L).name("2").parentId(0L).build());
list.add(RecDemoVO.builder().id(3L).name("3").parentId(0L).build());
list.add(RecDemoVO.builder().id(4L).name("1.1").parentId(1L).build());
list.add(RecDemoVO.builder().id(5L).name("1.2").parentId(1L).build());
list.add(RecDemoVO.builder().id(6L).name("1.2.1").parentId(5L).build());
list.add(RecDemoVO.builder().id(7L).name("2.1").parentId(2L).build());
list.add(RecDemoVO.builder().id(8L).name("2.1.1").parentId(7L).build());
list.add(RecDemoVO.builder().id(9L).name("2.1.1.1").parentId(8L).build());
return list;
}
[
{
"id": 1,
"name": "1",
"parentId": 0,
"children": [
{
"id": 4,
"name": "1.1",
"parentId": 1,
"children": null
},
{
"id": 5,
"name": "1.2",
"parentId": 1,
"children": [
{
"id": 6,
"name": "1.2.1",
"parentId": 5,
"children": null
}
]
}
]
},
{
"id": 2,
"name": "2",
"parentId": 0,
"children": [
{
"id": 7,
"name": "2.1",
"parentId": 2,
"children": [
{
"id": 8,
"name": "2.1.1",
"parentId": 7,
"children": [
{
"id": 9,
"name": "2.1.1.1",
"parentId": 8,
"children": null
}
]
}
]
}
]
},
{
"id": 3,
"name": "3",
"parentId": 0,
"children": null
}
]
