文章目录
递归循环构建树结构
public ApiResultDto<List<LocationDto>> getTreeByParams(LocationSearchDto searchDto, SecurityUser user) {
searchDto.setProjectId(user.getProjectId());
searchDto.setType(LocationType.BUILDING);
List<LocationEntity> locationEntities = locationDao.findByParams(searchDto);
List<LocationDto> locationDtos = locationEntities.stream().map(t -> {
LocationDto dto = new LocationDto();
dto.setId(t.getId());
dto.setName(t.getName());
dto.setType(t.getType());
dto.setSort(t.getSort());
dto.setSerialNum(t.getSerialNum());
dto.setCode(t.getCode());
dto.setParentId(t.getParentId());
iterChild(dto, user.getProjectId());
return dto;
}).collect(Collectors.toList());
return ApiResultDto.success(locationDtos);
}
private void iterChild(LocationDto dto, UUID projectId) {
List<LocationEntity> locations = locationDao.findChildById(dto.getId());
if (CollectionUtils.isEmpty(locations)) {
return;
}
List<LocationDto> locationDtos = locations.stream().map(t -> {
LocationDto childDto = new LocationDto();
childDto.setId(t.getId());
childDto.setName(t.getName());
childDto.setType(t.getType());
childDto.setSort(t.getSort());
childDto.setSerialNum(t.getSerialNum());
childDto.setCode(t.getCode());
childDto.setParentId(t.getParentId());
iterChild(childDto, projectId);
return childDto;
}).collect(Collectors.toList());
dto.setChildren(locationDtos);
}
hutool.TreeUtil.build构建树结构
public ApiResultDto<List<Tree<UUID>>> getTreeByParams(LocationSearchDto searchDto, SecurityUser user) {
searchDto.setProjectId(user.getProjectId());
List<LocationEntity> entities = locationDao.findByParams(searchDto);
List<LocationEntity> locationEntities = new ArrayList<>();
locationEntities.addAll(entities);
for (LocationEntity entity : entities) {
addParentEntities(entity, locationEntities);
}
locationEntities = locationEntities.stream().distinct().collect(Collectors.toList());
List<TreeNode<UUID>> nodeList = new ArrayList<>();
for (LocationEntity entity : locationEntities) {
TreeNode<UUID> treeNode = new TreeNode<>(entity.getId(), entity.getParentId(), entity.getName(), null);
nodeList.add(treeNode);
Map<String, Object> extra = new HashMap<>();
extra.put("name", entity.getName());
extra.put("serialNum", entity.getSerialNum());
extra.put("code", entity.getCode());
extra.put("type", entity.getType());
extra.put("sort", entity.getSort());
if (MapUtils.isNotEmpty(extra)) {
treeNode.setExtra(extra);
}
}
List<Tree<UUID>> result = TreeUtil.build(nodeList, null);
return ApiResultDto.success(result);
}
private void addParentEntities(LocationEntity entity, List<LocationEntity> res) {
if (Objects.nonNull(entity) && Objects.nonNull(entity.getParentId())) {
LocationEntity parentEntity = locationDao.selectById(entity.getParentId());
if (Objects.nonNull(parentEntity)) {
res.add(parentEntity);
addParentEntities(parentEntity, res);
}
}
}