java无限级分类的递归与循环

数据

CREATE TABLE `sys_dict`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `parent_id` bigint(20) DEFAULT NULL COMMENT '父ID',
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典名称',
  `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典编码',
  `val` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典键值',
  `sort` int(11) DEFAULT NULL COMMENT '字典排序',
  `create_time` datetime(0) DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime(0) DEFAULT NULL COMMENT '最后更新时间',
  `remarks` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '字典表' ROW_FORMAT = Dynamic;

数据

INSERT INTO `sys_dict` VALUES (1, 0, '博客类型', 'blog_push_type', NULL, 1, '2019-04-15 02:33:48', '2019-04-15 02:33:48', NULL);
INSERT INTO `sys_dict` VALUES (2, 1, '原创', 'blog_push_original', '0', 1, '2019-04-15 02:33:48', '2019-04-15 02:33:48', NULL);
INSERT INTO `sys_dict` VALUES (3, 2, '转载', 'blog_push_reprint', '1', 2, '2019-04-15 02:33:48', '2019-04-15 02:33:48', NULL);
INSERT INTO `sys_dict` VALUES (4, 3, '翻译', 'blog_push_translate', '2', 3, '2019-04-15 02:33:48', '2019-04-15 02:33:48', NULL);

实体类

package com.laolang.km.modules.admin.entity;

import com.alibaba.fastjson.annotation.JSONField;

import java.util.Date;

/**
 * 系统字典
 * @author laolang
 * @version 1.0
 * 2019/4/13 12:29
 */
public class SysDictEntity {


    @JSONField(ordinal = 1)
    private Long id;

    @JSONField(ordinal = 2)
    private Long parentId;

    @JSONField(ordinal = 3)
    private String name;

    @JSONField(ordinal = 4)
    private String code;

    @JSONField(ordinal = 5)
    private String val;

    @JSONField(ordinal = 6)
    private Integer sort;

    @JSONField(ordinal = 7,format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    @JSONField(ordinal = 8,format = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;

    @JSONField(deserialize = false,serialize = false)
    private String remarks;

    public SysDictEntity() {
    }

    
}

vo

package com.laolang.km.modules.admin.vo;

import com.alibaba.fastjson.annotation.JSONField;
import com.laolang.km.modules.admin.entity.SysDictEntity;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.List;

/**
 * 字典 ztree
 *
 * @author laolang
 * @version 1.0
 * 2019/4/15 2:08
 */
public class SysDictTreeVo {

    @JSONField(ordinal = 1)
    private Long id;

	@JSONField(ordinal = 2)
    private Long parentId;

    @JSONField(ordinal = 3)
    private String name;

    @JSONField(ordinal = 4)
    private String code;

    @JSONField(ordinal = 5)
    private String val;

    @JSONField(ordinal = 6)
    private Integer sort;

    @JSONField(ordinal = 7,format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    @JSONField(ordinal = 8,format = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;

    @JSONField(ordinal = 9)
    private List<SysDictTreeVo> children;

    public SysDictTreeVo() {
    }

    public static SysDictTreeVo entityToVo(SysDictEntity entity){
        SysDictTreeVo vo = new SysDictTreeVo();
        BeanUtils.copyProperties(entity,vo,"remarks");
        return vo;
    }

    
}

递归

    public List<SysDictTreeVo> getTree(){
        List<SysDictTreeVo> vos = new ArrayList<>();
        buildTreeData(vos,0L);
        return vos;
    }

    private boolean buildTreeData(List<SysDictTreeVo> root, Long parentId) {
        List<SysDictEntity> entities  = listByParentId(parentId);
        if (entities.size() > 0 ){
            for (SysDictEntity entity : entities) {
                SysDictTreeVo vo = SysDictTreeVo.entityToVo(entity);
                List<SysDictTreeVo> children = new ArrayList<>();
                if( buildTreeData(children,entity.getId())){
                    vo.setChildren(children);
                }else{
                    vo.setChildren(null);
                }
                root.add(vo);
            }
            return true;
        }
        return false;
    }

循环

参考:https://www.jianshu.com/p/c7d6f9a9f42d

    /**
     * 循环获取字典数据 树
     * 子ID必须小于父ID
     * 查询所有数据时必须按照ID从小到大排序
     *
     * @return
     */
    public List<SysDictTreeVo> getTreeData() {
        // 查询所有字典数据
        List<SysDictEntity> entities = listAll();
        // 转化为vo
        List<SysDictTreeVo> dictVos = new ArrayList<>();
        entities.forEach(entity -> dictVos.add(SysDictTreeVo.entityToVo(entity)));

        // 最终输出的树
        List<SysDictTreeVo> vos = new ArrayList<>();
        // 以ID为键保存每一条数据
        Map<Long, SysDictTreeVo> map = new HashMap<>();

        for (SysDictTreeVo dictVo : dictVos) {
            long pid = dictVo.getParentId();
            map.put(dictVo.getId(), dictVo);
            // 如果在map不存在当前数据的父ID为键的数据,则pid为0,保存在输出树中
            if (null == map.get(pid)) {
                vos.add(dictVo);
            } else {
                // 如果在map存在当前数据的父ID为键的数据,则将当前数据加入到父节点的children中
                SysDictTreeVo vo = map.get(pid);
                if (null == vo.getChildren()) {
                    vo.setChildren(new ArrayList<>());
                }
                vo.getChildren().add(dictVo);
            }
        }

        return vos;
    }

另一种方式

实体类

package com.laolang.shopboot.business.catalog.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Date;

@ApiModel("catalog - 商品分类")
@TableName("catalog_product_cate")
@Accessors(chain = true)
@Data
public class ProductCate {

    @TableId(value = "id", type = IdType.INPUT)
    @ApiModelProperty(value = "id")
    private Long id;

    @ApiModelProperty(value = "分类名称")
    private String name;

    @ApiModelProperty(value = "父id")
    private Long parentId;

    @ApiModelProperty(value = "排序")
    private Integer sort;

    @ApiModelProperty(value = "createTime")
    private Date createTime;

    @ApiModelProperty(value = "updateTime")
    private Date updateTime;

    @Version
    @ApiModelProperty(value = "version", hidden = true)
    private Integer version;
}

实现过程

    @Override
    public List<ProductCateTreeVo> tree() {
    	// 查出所有
        List<ProductCate> entityList = productCateService.list();
        if (CollUtil.isEmpty(entityList)) {
            return new ArrayList<>();
        }
        ProductCateMapStructMapper productCateMapStructMapper = getProductCateMapStructMapper();
        // 根分类
        List<ProductCateTreeVo> tree = entityList.stream()
                .filter(entity -> 0L == entity.getParentId())
                .map(productCateMapStructMapper::entity2treeVo)
                .collect(Collectors.toList());
        // 分类树map缓存
        Map<Long, ProductCateTreeVo> treeMap = tree.stream().collect(Collectors.toMap(ProductCateTreeVo::getId, t -> t));
        // 非根分类按照paretnId和sort排序
        List<ProductCate> cateNotRootList = entityList.stream()
                .filter(t -> 0L != t.getParentId())
                .sorted(Comparator.comparing(ProductCate::getParentId).thenComparing(ProductCate::getSort))
                .collect(Collectors.toList());
        // 非根分类添加到树中
        if (CollUtil.isNotEmpty(cateNotRootList)) {
            cateNotRootList.forEach(node -> {
                ProductCateTreeVo parent = treeMap.get(node.getParentId());
                if (null != parent) {
                    if (CollUtil.isEmpty(parent.getChildren())) {
                        parent.setChildren(new ArrayList<>());
                    }
                    ProductCateTreeVo treeNode = productCateMapStructMapper.entity2treeVo(node);
                    parent.getChildren().add(treeNode);
                    treeMap.put(treeNode.getId(), treeNode);
                }
            });
        }

        return tree;
    }

你可能感兴趣的:(km)