目录构造工具类

发布时间 2024-01-09 16:15:32作者: xietingweia
package com.haizhi.kg.utils.vo;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * 目录
 *
 * @author : XIETINGWEI
 * @date : 2024-1-8
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Catalog implements Serializable {

    @ApiModelProperty("编号")
    private String id;

    @ApiModelProperty("名称")
    private String label;

    @ApiModelProperty("编码")
    private String value;

    @ApiModelProperty("层级")
    private Integer level;

    @ApiModelProperty("上级名称")
    private String parentName;

    @ApiModelProperty("上级code")
    private String parentCode;

    @ApiModelProperty("是否叶子节点 1:是 0:不是")
    private String isLeaf;

    @ApiModelProperty("子节点")
    private List<Catalog> children;
}
package com.haizhi.kg.utils;

import com.haizhi.kg.utils.vo.Catalog;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 目录构造工具类
 * @author: XIETINGWEI
 * @date: 2024/1/8
 */
public class CatalogUtil {

    public static List<Catalog> catalogList = new ArrayList<>();

    /**
     * @param sourceList 必需字段: label,value,parentName,parentCode(无上级时:code为0或空)  (类型:String)
     * @return
     */
    public static <T> List<Catalog> buildCatalog(List<T> sourceList) {
        catalogList.clear();
        // 初始化 映射
        catalogList = sourceList.stream().map(obj -> {
            Catalog catalog = new Catalog();
            BeanUtils.copyProperties(obj, catalog);
            catalog.setChildren(new ArrayList<>());
            return catalog;
        }).collect(Collectors.toList());

        List<Catalog> roots = catalogList.stream().filter(obj -> {
            return StringUtils.equals(obj.getParentCode(), "0") || ObjectUtils.isEmpty(obj.getParentCode());
        }).collect(Collectors.toList());
        for (Catalog root : roots) {
            buildChildren(root);
        }
        return roots;
    }

    private static void buildChildren(Catalog node) {
        List<Catalog> children = findByParent(node);
        for (Catalog child : children) {
            buildChildren(child);
        }
        if (!ObjectUtils.isEmpty(children)) {
            node.setChildren(children);
            node.setIsLeaf("0");
        } else {
            node.setIsLeaf("1");
        }
    }

    private static List<Catalog> findByParent(Catalog parent) {
        List<Catalog> list = CatalogUtil.catalogList.stream().filter(obj -> {
            return StringUtils.equals(obj.getParentCode(), parent.getValue());
        }).collect(Collectors.toList());
        return list;
    }
}