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;
    }
无限树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值