Table of contents
1. Prepare classification data
Please see the previous article for classification data
https://blog.csdn.net/weixin_58403235/article/details/129635380
2. Realize
The code is as follows (example):
@Autowired
CourseMapper courseMapper;
@Override
//递归查询数据
public List<Course> selectTree(){
//获取所有课程数据,避免循环查表 消耗大量资源
List<Course> list = courseMapper.selectList(null);
List<Course> collect = list.stream()
//filter有几个匹配的就有几个列表元素
.filter(item -> item.getParentId().equals("0"))
.map(menu -> {
menu.setCourseList(getChildren(menu, list));
return menu;
}).collect(Collectors.toList());
return collect;
}
private List<Course> getChildren(Course root, List<Course> list) {
List<Course> chirden = list.stream()
.filter(item -> item.getParentId().equals(root.getId()))
.map(menu -> {
menu.setCourseList(getChildren(menu, list));
return menu;
}).collect(Collectors.toList());
return chirden;
}
test:
@Test
void testCourseService() {
List<Course> courses = courseService.selectTree();
//因为ParentCid为0的只有一个 所以该列表下只有一个元素
Course course = courses.get(0);
System.out.println(course);
}
The result is shown in the figure:
Summarize
In this chapter, the recursive operation of Java method is implemented to query the tree-type classification data. In fact, the classification data can also be obtained by circular table lookup, but the efficiency of circular table lookup is too low for wow, so there is no choice.