@Data
public class SysStoreCategoryDto implements Serializable {
private Integer id;
/** 父id */
private Integer pid;
/** 名称 */
private String cateName;
/** 排序 */
private Integer sort;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<SysStoreCategoryDto> children;
}
public Object buildTree(List<SysStoreCategoryDto> categoryDTOList) {
Set<SysStoreCategoryDto> trees = new LinkedHashSet<>();
Set<SysStoreCategoryDto> cates= new LinkedHashSet<>();
List<String> deptNames = categoryDTOList.stream().map(SysStoreCategoryDto::getCateName)
.collect(Collectors.toList());
SysStoreCategoryDto categoryDTO = new SysStoreCategoryDto();
Boolean isChild;
for (SysStoreCategoryDto deptDTO : categoryDTOList) {
isChild = false;
if ("0".equals(deptDTO.getPid().toString())) {
trees.add(deptDTO);
}
for (SysStoreCategoryDto it : categoryDTOList) {
if (it.getPid().equals(deptDTO.getId())) {
isChild = true;
if (deptDTO.getChildren() == null) {
deptDTO.setChildren(new ArrayList<SysStoreCategoryDto>());
}
deptDTO.getChildren().add(it);
}
}
if(isChild)
cates.add(deptDTO);
else if(!deptNames.contains(sysStoreCategoryRepository.findNameById(deptDTO.getPid())))
cates.add(deptDTO);
}
if (CollectionUtils.isEmpty(trees)) {
trees = cates;
}
Integer totalElements = categoryDTOList!=null?categoryDTOList.size():0;
Map map = new HashMap();
map.put("totalElements",totalElements);
map.put("content",CollectionUtils.isEmpty(trees)?categoryDTOList:trees);
return map;
}