java返回树形结构关键字搜索结构
作者:互联网
1、我们平时开发都会遇到返回树形结构数据,很多时候写的方式很慢,我写一种较快的方式,如有bug请各位大佬指出
首先一个接口,参数keyWord
返回结果对象
Group对象就是自己需要的字段
1、实现思路:
1.1、先根据keyWord查询所有结果,普通的sql
1.2、循环遍历子级
循环先遍历所有结果集,以parentId根节点作为基础,我这里用“0”作为根节点
把遍历的结果集收集到新的list对象,如果keyWord为空时,就返回所有的树形结果,否则就只返回关键字结果集(非树形)
1.3、然后调用递归
上图 这里再遍历每一个子级,把子级添加到自己子级下面(关键)
1.4、测试结果如下:
keyWord不为空时查找的结果:
keyWord为空时结果:
{ "data": [ { "id": "1", "appId": "21", "parentId": "0", "name": "1eww", "code": "32", "sort": 0, "delFlag": 0, "createBy": "11", "createTime": "2022-09-07T18:12:20", "updateBy": null, "updateTime": "2022-09-07T18:12:20", "children": [ { "id": "2", "appId": "21", "parentId": "1", "name": "dds", "code": "22", "sort": 0, "delFlag": 0, "createBy": "21", "createTime": "2022-09-07T18:12:38", "updateBy": null, "updateTime": "2022-09-07T18:12:38", "children": [ { "id": "3", "appId": "21", "parentId": "2", "name": "ew", "code": "33", "sort": 0, "delFlag": 0, "createBy": "3", "createTime": "2022-09-07T18:12:54", "updateBy": null, "updateTime": "2022-09-07T18:12:54", "children": null } ] } ] }, { "id": "4", "appId": "21", "parentId": "0", "name": "rreee", "code": "w", "sort": 0, "delFlag": 0, "createBy": "4", "createTime": "2022-09-07T18:38:42", "updateBy": null, "updateTime": "2022-09-07T18:38:42", "children": null } ], "type": "success", "code": "200", "msg": "处理成功", "cause": null, "date": "2022-09-09T10:44:53.378+00:00", "spent": 48, "count": 0, "pageSize": 0, "pageNumber": 0, "totalPages": 0 } |
这种方式在数据量较大或者子级较多的时候,比纯sql的restMap方式快很多
标签:code,07T18,java,09,关键字,树形,2022,12,null 来源: https://www.cnblogs.com/InterfaceAOP/p/16673739.html