递归生成树型结构


import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 树形结构
 */
@Data
public class TreeTypeDTO {

    @ApiModelProperty(value = "ID",required = true)
    private String id;

    @ApiModelProperty(value = "名称",required = true)
    private String name;

    @ApiModelProperty(value = "子集",required = true)
    private List<TreeTypeDTO> children;

    @ApiModelProperty(value = "父级id")
    @JsonIgnore
    private String parentId;

    /**
     * 生成树型结构
     * @param list
     * @return
     */
    public static List<TreeTypeDTO> listToTree(List<TreeTypeDTO> list) {
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        //用递归找子。
        List<TreeTypeDTO> treeList = new ArrayList<>();
        for (TreeTypeDTO tree : list) {
            //根目录的parentId为null ,-1
            if (StringUtils.isBlank(tree.getParentId()) || StringUtils.equals(tree.getParentId(),"-1")){
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }


    private static TreeTypeDTO findChildren(TreeTypeDTO tree, List<TreeTypeDTO> list) {
        for (TreeTypeDTO node : list) {
            if (StringUtils.equals(node.getParentId(),tree.getId())){
                if (CollectionUtils.isEmpty(tree.getChildren())){
                    tree.setChildren(new ArrayList<>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }
}

1.里面又swagger注解,lombok 注解,使用时可以删除。

2.字段 id,parentId 为判断字段,children 装入子集。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

痕0712

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值