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

text
1 2 3 4
  算法1:递归算法


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

一、数据库设计:

实例中的重要字段:

二、算法1:递归算法

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
public List<ProductType> treeData() {
      // 方案一:通过递归的方式来获得菜单
      return getTreeDataRecursion(0L);
  
}

// 递归方法,调用此方法时候,将 0 传入,0代表一级菜单
private List<ProductType> getTreeDataRecursion(long id) {
      // 获取所有的子级
      Wrapper<ProductType> wrapper = new EntityWrapper<>();
      wrapper.eq("pid", id);
      List<ProductType> productTypes = selectList(wrapper);

      // 判断子级是否还有子级
      if (productTypes == null || productTypes.size() < 1) {
         // 如果没有子级则返回空
         return null;
      }
      // 循环获得的子级,将子级放入父级中
      for (ProductType productType : productTypes) {
         // 递归方法,自己调用自己
         List<ProductType> treeDataRecursion = getTreeDataRecursion(productType.getId());
         // 将子级放入父级中
         productType.setChildren(treeDataRecursion);
      }
      // 返回菜单集合
      return productTypes;
}

三、算法2:循环算法(这是优化算法)

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 public List<ProductType> treeData() {

      // 方案二:通过循环的方式获得菜单。这里将 0 传入,因为0在此次数据表中代表一级菜单
      List<ProductType> dataLoop = getTreeDataLoop(0L);
      return dataLoop;    
 }

 // 优化算法
 private List<ProductType> getTreeDataLoop(long id) {
      // 新建一个list来存放一级菜单
      List<ProductType> tree = new ArrayList<>();

      Wrapper<ProductType> wrapper = new EntityWrapper<>();
      // 获取所有的菜单数据
      List<ProductType> productTypes = selectList(wrapper);

      Map<Long, ProductType> map = 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;
 }

三、测试结果


原文地址:https://blog.csdn.net/suprezheng/article/details/86500867?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168475004016800197081290%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168475004016800197081290&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-8-86500867-null-null.142^v87^insert_down1,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96