java 从数据库读取菜单,java从数据库中读取数据-生成菜单树tree之算法优化

这里介绍两种从数据库总读取数据生成菜单树的算法:

算法1:递归算法

算法2:循环算法(推荐--优化算法)

一、数据库设计:

2aa2cc6ab3333aa62abd893f0b7822c0.png

实例中的重要字段:

0d90516ab1f34cfd594288b2248d3c60.png

二、算法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;

}

三、测试结果

35abdfab2467d43e83d5f5642e920b34.png

e48a6e34de6fc6faf3909338a1d419f5.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值