前言
- 开发中树形结构应该是很常见的一种数据结构了。而在数据库方面往往也都伴随相应的树形设计。在
mysql
中通过 parent_id
来绑定其上游,从而达到树形结构的存储,但是在查询的过程中就需要我们将 List
列表转成我们理想中的 Tree
树。
构建树
List<Location> locations = this.baseMapper.selectList(queryWrapper);
Map<String, List<Location>> collect = locations.stream().collect(Collectors.groupingBy(Location::getId));
List<QueryLocationDto> resultList = new ArrayList<>();
List<Location> parentLocation = getParentLocation(1, collect, id);
if (CollectionUtils.isNotEmpty(parentLocation)) {
for (Location location : parentLocation) {
QueryLocationDto dto = new QueryLocationDto();
BeanUtils.copyProperties(location, dto);
resultList.add(dto);
}
}
复制代码
private List<Location> getParentLocation(int level, Map<String, List<Location>> collect, String id) {
List<Location> locationList = new ArrayList<>();
if (collect.containsKey(id)) {
Location location = collect.get(id).get(0);
locationList.add(location);
String superid = location.getSuperid();
locationList.addAll(getParentLocation(level + 1, collect, superid));
}
return locationList;
}
复制代码
- 相信大部分我们 都是通过
Java
来处理的。 其中 getParentLocation
就是用递归不断的去构建上下级关系。这种方式也是我比较推荐的,因为这样就把职责分