0

TreeUtils工具类一行代码实现列表转树 实战Java8 三级菜单 三级分类 附视频 - 赛先生...

 1 year ago
source link: https://www.cnblogs.com/javazhishitupu/p/16902479.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在日常一线开发过程中,总有列表转树的需求,几乎是项目的标配,比方说做多级菜单、多级目录、多级分类等,有没有一种通用且跨项目的解决方式呢?帮助广大技术朋友给业务瘦身,提高开发效率。

本文将基于Java8的Lambda 表达式和Stream等知识,使用TreeUtils工具类实现一行代码完成列表转树这一通用型需求。本文有配套视频,传送门直达。

二、实战编码

1、引入坐标

本坐标地址包含TreeUtils工具类方法,已经发布到Maven中央仓库,建议使用最新的版本号,本文法布施版本是1.5.8

学习源码的朋友,源码直通车

<dependency>
    <groupId>xin.altitude.cms</groupId>
    <artifactId>ucode-cms-common</artifactId>
    <version>1.5.8</version>
</dependency>
2、实现接口

列表实体类实现ITreeEntity并实现抽象方法。

/**
 * 类别表
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "bu_category")
public class Category implements ITreeEntity<String> {
    private static final long serialVersionUID = 1L;
    @TableId(type = IdType.AUTO)
    private String id;
    private String name;
    private String parentId;
}
3、调用TreeUtils工具类

在服务层调用TreeUtils工具类,一行代码完成转换。

public List<TreeNode<String>> selectCategoryList2() {
    List<Category> list = this.list();
    // 一行代码实现列表转树结构 通用型代码 能够跨项目使用 业务解藕
    return TreeUtils.createNode(list, "000000");
}
4、效果展示

原始列表数据

{
  "code": 200,
  "msg": "操作成功",
  "data": [
    {
      "id": "310000",
      "name": "电子商务",
      "parentId": "000000"
    },
    {
      "id": "310100",
      "name": "大宗商品",
      "parentId": "310000"
    },
    {
      "id": "310101",
      "name": "大宗商品综合",
      "parentId": "310100"
    },
    {
      "id": "310102",
      "name": "钢铁类电商",
      "parentId": "310100"
    }
  ]
}

树状层次数据

{
  "code": 200,
  "msg": "操作成功",
  "data": [
    {
      "id": "310000",
      "name": "电子商务",
      "childList": [
        {
          "id": "310100",
          "name": "大宗商品",
          "childList": [
            {
              "id": "310101",
              "name": "大宗商品综合",
              "childList": []
            },
            {
              "id": "310102",
              "name": "钢铁类电商",
              "childList": []
            }
          ]
        }
      ]
    }
  ]
}

通过一个小小的高频业务场景,抽离业务共性,屏蔽业务细节,实现了通用型业务逻辑的编码。

希望广大技术朋友在完成日常开发工作的前提下,能够进一步打磨代码,感受编程之美。

喜欢本文就【♥️推荐♥️】一下,激励我持续创作。这个Github同样精彩,收到您的star我会很激动。本文归档在专题博客,视频讲解在B站


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK