有时需要将数据处理成树形结构,如果数据是一张表内以 id,parentId的形式,可以看看这篇
java8使用stream流将数据处理成树状结构(非递归)
如果数据是两张表A B,B表的parentId对应A表的id这种形式,可以用下面的方法:
章节表 小节表
一个章节可以有多个小节
public List<ChapterVo> getChapterVideoByCourseId() {
// 章节信息
List<EduChapter> eduChapterList = eduChapterService.list(null);
// 小节信息
List<EduVideo> eduVideoList = eduVideoService.list(null);
List<ChapterVo> chapterVoList = eduChapterList.stream().map(item1 -> {
ChapterVo chapterVo = new ChapterVo();
BeanUtils.copyProperties(item1, chapterVo);
List<VideoVo> videoVoList = eduVideoList.stream()
.filter(item2 -> item1.getId().equals(item2.getChapterId()))
.map(item3 -> {
VideoVo videoVo = new VideoVo();
BeanUtils.copyProperties(item3, videoVo);
return videoVo;
}).collect(Collectors.toList());
chapterVo.setChildren(videoVoList);
return chapterVo;
}).collect(Collectors.toList());
return chapterVoList;
}
返回的数据格式:
"data":
[
{
"id": "1181729226915577857",
"title": "第七章:I/O流",
"children": [
{
"id": "1189471423678939138",
"title": "test",
"free": null
},
{
"id": "1189476403626409986",
"title": "22",
"free": null
}
]
},
{
"id": "15",
"title": "第一章:Java入门",
"children": [
{
"id": "17",
"title": "第一节:Java简介",
"free": null
},
{
"id": "18",
"title": "第二节:表达式和赋值语句",
"free": null
},
{
"id": "19",
"title": "第三节:String类",
"free": null
},
{
"id": "20",
"title": "第四节:程序风格",
"free": null
}
]
}
]