前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 分组数据结构组装

Java 分组数据结构组装

作者头像
赵哥窟
发布2021-05-17 14:19:54
9730
发布2021-05-17 14:19:54
举报
文章被收录于专栏:日常技术分享日常技术分享

这只是初级水平吧,也许还有更好的方式实现。这里只是记录一下。如果有好的实现方法可以交流。

截屏2021-05-12 10.16.03.png

如图原始的数据结构是这样的,前端需要的结构是这样的,就是把相同groupId相同的数据放到一个数组下面。在包一层groupId。

代码语言:javascript
复制
{
  "code": 0,
  "error": "",
  "trace": "",
  "result": [
    {
      "groupId": 4,
      "groutName": "新增分组测试",
      "children": [
        {
          "id": 7,
          "name": "新增静态Api(更新)"
        }
      ]
    },
    {
      "groupId": 5,
      "groutName": "新增分组测试1",
      "children": [
        {
          "id": 8,
          "name": "新增静态Api-1"
        }
      ]
    }
  ],
  "successful": true
}

实现

返回前端需要的对象
代码语言:javascript
复制
public class ApiDTO {

    /**
     * Api树形结构对象
     */
    @Getter
    @Setter
    public static class ApiTree implements Serializable {

        @ApiModelProperty(value = "分组Id", example = "")
        private Integer groupId;

        @ApiModelProperty(value = "分组名称", example = "")
        private String groutName;

        @ApiModelProperty(value = "所有Api")
        private List<ApiBase> children;
    }

    /**
     * 分类树形结构对象
     */
    @Getter
    @Setter
    public static class ApiBase implements Serializable {

        @ApiModelProperty(value = "apiId", example = "")
        private Integer id;

        @ApiModelProperty(value = "api 名称", example = "")
        private String name;
    }

}
实现
代码语言:javascript
复制
//获取所有的数据
List<ApiBaseGroupDTO> groupDTOList = apiBaseMapper.getAllApiGroupByName(param.getApiName());
//按GroupId分组
Map<Integer, List<ApiBaseGroupDTO>> groupMap = groupDTOList.stream().collect(Collectors.groupingBy(it -> it.getGroupId()));

//转前端需要的树结构对象
List<ApiDTO.ApiTree> treeList = groupDTOList.stream().map(it -> {
    ApiDTO.ApiTree apiTree = new ApiDTO.ApiTree();
    apiTree.setGroupId(it.getGroupId());
    apiTree.setGroutName(it.getGroutName());
    return apiTree;
}).collect(Collectors.toList());

//每个节点添加上子节点
treeList.forEach(it -> {
    List<ApiDTO.ApiBase> apiList = groupMap.get(it.getGroupId()).stream().map(api -> {
        ApiDTO.ApiBase apiBase = new ApiDTO.ApiBase();
        apiBase.setId(api.getId());
        apiBase.setName(api.getName());
        return apiBase;
    }).collect(Collectors.toList());
    it.setChildren(apiList);
});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 返回前端需要的对象
  • 实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档