当前位置:网站首页>Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.
Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.
2022-06-24 00:56:00 【XuDream】
List of articles
Use scenarios
In the development and implementation of the user's position 、 Job list display , Display the menu directory of users on the background management page .
One 、 Effect display
1. database structure :
for example : Electronic products, / laptop / Lenovo notebook Generate a three-level Directory 
2. Data processing returns :
{
"code": 200,
"msg": " Successful operation ",
"data": [
{
"id": "1",
"name": " Electronic products, ",
"parentId": "0",
"type": 1,
"childList": [
{
"id": "5",
"name": " laptop ",
"parentId": "1",
"type": 2,
"childList": [
{
"id": "21",
"name": " Lenovo notebook ",
"parentId": "5",
"type": 3,
"childList": []
},
{
"id": "22",
"name": " Alien notebook ",
"parentId": "5",
"type": 3,
"childList": []
},
{
"id": "23",
"name": " Dell notebook ",
"parentId": "5",
"type": 3,
"childList": []
}
]
},
{
"id": "6",
"name": " mobile phone ",
"parentId": "1",
"type": 2,
"childList": [
{
"id": "24",
"name": " Apple mobile phone ",
"parentId": "6",
"type": 3,
"childList": []
},
{
"id": "25",
"name": " Pineapple mobile phone ",
"parentId": "6",
"type": 3,
"childList": []
}
]
},
{
"id": "7",
"name": " The headset ",
"parentId": "1",
"type": 2,
"childList": []
},
{
"id": "8",
"name": " Electronic cigarettes ",
"parentId": "1",
"type": 2,
"childList": []
}
]
},
{
"id": "2",
"name": " Articles for daily use ",
"parentId": "0",
"type": 1,
"childList": [
{
"id": "10",
"name": " The chair ",
"parentId": "2",
"type": 2,
"childList": []
},
{
"id": "11",
"name": " The bed ",
"parentId": "2",
"type": 2,
"childList": []
},
{
"id": "19",
"name": " toothpaste ",
"parentId": "2",
"type": 2,
"childList": []
},
{
"id": "20",
"name": " toothbrush ",
"parentId": "2",
"type": 2,
"childList": []
},
{
"id": "9",
"name": " Table ",
"parentId": "2",
"type": 2,
"childList": []
}
]
},
{
"id": "3",
"name": " Hygienic Products ",
"parentId": "0",
"type": 1,
"childList": [
{
"id": "12",
"name": " toilet paper ",
"parentId": "3",
"type": 2,
"childList": []
},
{
"id": "13",
"name": " Wipes ",
"parentId": "3",
"type": 2,
"childList": []
}
]
},
{
"id": "4",
"name": " School Supplies ",
"parentId": "0",
"type": 1,
"childList": [
{
"id": "14",
"name": " e-book ",
"parentId": "4",
"type": 2,
"childList": []
},
{
"id": "15",
"name": " Listening CD ",
"parentId": "4",
"type": 2,
"childList": []
},
{
"id": "16",
"name": " Physical book ",
"parentId": "4",
"type": 2,
"childList": []
},
{
"id": "17",
"name": " Pen ",
"parentId": "4",
"type": 2,
"childList": []
},
{
"id": "18",
"name": " Notebook ",
"parentId": "4",
"type": 2,
"childList": []
}
]
}
]
}
Two 、 Realize the idea
- Get all categories .
- Get all categories id aggregate . Use stream() Realization ,stream Use the tutorial
- Get level 1 Classification Information . Also use stream() Realization .
- Circular primary classification , Add a subcategory to the first level classification in the loop , And add the first level classification to the returned tree structure ( remarks : Do not join the returned tree structure , Return directly to step 3 The classification information of ).
- The focus is on the steps 4 Add a subcategory to the first level classification , And subcategories are adding subcategories , Sub sub sub classification and add sub sub sub classification ·········· wait , The implementation process can use recursion .
- step 5 Implementation process : Write a recursive method , Add child nodes to the current node , First, get the byte point set of the current node , Then put this set into the current node sub node attribute , Then call the current recursive method again , Treat the newly obtained child node as the new current node , Get the new child node of the new current node , Be careful Call the current recursive method again , Treat the newly obtained child node as the new current node First, judge whether the new current node has child nodes ( Judgment method : Get the word node array of the current node , According to the size()>0? Determine whether there are child nodes ), If not, there is no need for recursion .
- summary :1-4 It's data preparation ,5-6 Is to implement recursion ( Recursion of adding child nodes to the current node ).
3、 ... and 、 Code display
1. Main idea code
@GetMapping("/list")
public Result list() {
// All categories
List<Category> categoryList = categoryService.list();
// All categories id aggregate
List<String> idList = categoryList.stream().map(Category::getId).collect(Collectors.toList());
// Returned tree classification results
List<Category> treeCategory = new ArrayList<>();
// First level classification catalogue
List<Category> categories = categoryList.stream().filter(category -> !idList.contains(category.getParentId())).collect(Collectors.toList());
// Cycle through the current level-1 catalog
for (Category category : categories) {
// To the current classification node add to Sub classification node
addChild(categoryList,category);
// After adding child node classifications to the current classification , Add to the returned tree structure
treeCategory.add(category);
}
// Return the returned tree structure
return Result.success(categories);
}
/** * To the current classification node add to Sub classification node * @param categoryList All categories * @param category Current classification node */
public void addChild( List<Category> categoryList,Category category){
// Cycle through all categories , Get all the children of the current node
List<Category> categoryListChild = categoryList.stream().filter(category1 -> category1.getParentId().equals(category.getId())).collect(Collectors.toList());
// Add the child nodes of the current category to the current category
category.setChildList(categoryListChild);
// Call this method again , Treat the child nodes of the current node as the current node , Continue adding child nodes , remarks : This will cause a constant cycle
categoryListChild.forEach(category1 -> {
// Add next step , Judge whether the current node has child nodes , No loop recursion
//if ()
addChild(categoryList,category1);
});
}
/** * Judge the current node Whether there is Child node * @param categoryList All categories * @param category Current node */
public boolean haveChild( List<Category> categoryList,Category category){
// Get the children of the current node
List<Category> categoryListChild = categoryList.stream().filter(category1 -> category1.getParentId().equals(category.getId())).collect(Collectors.toList());
// The child node is greater than 0 There is , Otherwise, it doesn't exist
return categoryListChild.size()>0?true:false;
}
2. Entity class code presentation
remarks : There must be an array of child nodes in the entity class code . Entity class pairs use the top entity class image
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
/** * Category name */
private String name;
/** * The superior id */
private String parentId;
/** * Classification level */
private Integer type;
/** * Array of child nodes */
@TableField(exist = false)
private List<Category> childList;
}
边栏推荐
- [Hongke case] how can 3D data become operable information Object detection and tracking
- C语言:递归实现N的阶乘
- 实时计算框架:Spark集群搭建与入门案例
- WinSCP和PuTTY的安装和使用
- Andorid development art exploration notes (2), cross platform applet development framework
- 【Flutter】如何使用Flutter包和插件
- ShardingSphere-proxy-5.0.0容量范围分片的实现(五)
- 用一个软件纪念自己故去的母亲,这或许才是程序员最大的浪漫吧
- setfacl命令的基本用法
- 逻辑的定义
猜你喜欢

C语言:利用自定义函数排序

Interview notes for Android outsourcing workers for 3 years. You still need to go to a large factory to learn and improve when you have the opportunity. Interview questions for Android Development Int

LSF打开Job idle information以看job的cpu time/elapse time使用情况

Real time computing framework: Spark cluster setup and introduction case

【小程序】实现双列商品效果

skywalking 安装部署实践

Real time computing framework: Flink cluster construction and operation mechanism

苹果Iphone14搭载北斗导航系统,北斗VS GPS有哪些优势?

Social recruitment interview is indispensable -- 1000 interview questions for Android engineers from Internet companies

GNN上分利器!与其绞尽脑汁炼丹,不如给你的GNN撒点trick吧
随机推荐
Is it safe to open an account for shares of tongdaxin?
[CVPR 2020 oral] a physics based noise formation model for extreme low light raw denoising
After the deployment of Beidou navigation system, why didn't we launch a high-precision map similar to Google maps?
小猫爪:PMSM之FOC控制15-MRAS法
Andorid development art exploration notes (2), cross platform applet development framework
What problems need to be solved by MES management system in the era of intelligent manufacturing
【小程序】编译预览小程序时,出现-80063错误提示
ShardingSphere-proxy-5.0.0容量范围分片的实现(五)
【ICCV Workshop 2021】基于密度图的小目标检测:Coarse-grained Density Map Guided Object Detection in Aerial Images
Social order in the meta universe
产业互联网时代将依靠源自于产业本身的产品、技术和模式来实现的
[applet] realize the effect of double column commodities
Open source model library of flying propeller industry: accelerating the development and application of enterprise AI tasks
[SPRS J P & RS 2022] small target detection module: a normalized Gaussian Wasserstein distance for tiny object detection
[Hongke case] how can 3D data become operable information Object detection and tracking
C语言:递归实现N的阶乘
Relationship between continuous testing and quality assurance
kubernetes之常用核心资源对象
numpy. linalg. Lstsq (a, B, rcond=-1) parsing
Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)