List<T>根据父级id组装树形结构

@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;
    }

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值