这里介绍两种从数据库总读取数据生成菜单树的算法:
算法1:递归算法
算法2:循环算法(推荐--优化算法)
一、数据库设计:
实例中的重要字段:
二、算法1:递归算法
public ListtreeData() {
// 方案一:通过递归的方式来获得菜单
return getTreeDataRecursion(0L);
}
// 递归方法,调用此方法时候,将 0 传入,0代表一级菜单
private ListgetTreeDataRecursion(long id) {
// 获取所有的子级
Wrapperwrapper = new EntityWrapper<>();
wrapper.eq("pid", id);
ListproductTypes = selectList(wrapper);
// 判断子级是否还有子级
if (productTypes == null || productTypes.size() < 1) {
// 如果没有子级则返回空
return null;
}
// 循环获得的子级,将子级放入父级中
for (ProductType productType : productTypes) {
// 递归方法,自己调用自己
ListtreeDataRecursion = getTreeDataRecursion(productType.getId());
// 将子级放入父级中
productType.setChildren(treeDataRecursion);
}
// 返回菜单集合
return productTypes;
}
三、算法2:循环算法(这是优化算法)
public ListtreeData() {
// 方案二:通过循环的方式获得菜单。这里将 0 传入,因为0在此次数据表中代表一级菜单
ListdataLoop = getTreeDataLoop(0L);
return dataLoop;
}
// 优化算法
private ListgetTreeDataLoop(long id) {
// 新建一个list来存放一级菜单
Listtree = new ArrayList<>();
Wrapperwrapper = new EntityWrapper<>();
// 获取所有的菜单数据
ListproductTypes = selectList(wrapper);
Mapmap = new HashMap<>();
// 将所有的数据,以键值对的形式装入map中
for (ProductType productType : productTypes) {
map.put(productType.getId(), productType);
}
for (ProductType productType : productTypes) {
// 如果id是父级的话就放入tree中
if (productType.getPid().longValue() == id) {
tree.add(productType);
} else {
// 子级通过父id获取到父级的类型
ProductType parent = map.get(productType.getPid());
// 父级获得子级,再将子级放到对应的父级中
parent.getChildren().add(productType);
}
}
return tree;
}
三、测试结果