如何快速、且易懂编写Java递归生成树形菜单结构

Java stream处理递归

更新完整代码

private void queryLevelCategory(List<KnowledgeCategory> categoryList){
        // 可以是顶级thetopuuid0000000000000000000000 或者某个分类查子集
        List<KnowledgeCategory> knowledgeCategories = this.deepCategory("thetopuuid0000000000000000000000", categoryList);
        String s = JsonUtil.toJson(knowledgeCategories);
        System.out.println(s);
    }

    private List<KnowledgeCategory> deepCategory(String uuid,List<KnowledgeCategory> categoryList){
        List<KnowledgeCategory>    result = new ArrayList<>();
        categoryList.forEach(x->{
            if (uuid.equals(x.getParentUuid())) {
                List<KnowledgeCategory> childRenList = this.deepCategory(x.getUuid(), categoryList);
                x.setChildRen(childRenList);
                result.add(x);
            }
        });
        return result;
    }

文件上传中...

响应json数据

[
  {
    "uuid": "category000000000000000000000009",
    "categoryName": "知识管理默认一级分类(2)",
    "parentUuid": "thetopuuid0000000000000000000000",
    "describeInfo": "知识管理默认一级分类",
    "lever": 1,
    "childRen": [
      {
        "uuid": "category000000000000000000000010",
        "categoryName": "知识管理默认二级分类(1)",
        "parentUuid": "category000000000000000000000009",
        "describeInfo": "知识管理默认二级分类",
        "lever": 2,
        "childRen": []
      }
    ]
  },
  {
    "uuid": "z4440a5127f0492ab3eaeb1a4a98406f",
    "categoryName": "1233(0)",
    "parentUuid": "thetopuuid0000000000000000000000",
    "describeInfo": "",
    "lever": 1,
    "childRen": [
      {
        "uuid": "d5b4dc296a5e47c8bb546fe1ac3a5446",
        "categoryName": "3无123213(0)",
        "parentUuid": "z4440a5127f0492ab3eaeb1a4a98406f",
        "describeInfo": "",
        "lever": 2,
        "childRen": [
          {
            "uuid": "i7f477bfbf3f44a797efeae830212320",
            "categoryName": "tttt(0)",
            "parentUuid": "d5b4dc296a5e47c8bb546fe1ac3a5446",
            "describeInfo": "",
            "lever": 3,
            "childRen": [
              {
                "uuid": "r1f1b3deaf224ea4a3cd732f4d59c43a",
                "categoryName": "bb(0)",
                "parentUuid": "i7f477bfbf3f44a797efeae830212320",
                "describeInfo": "",
                "lever": 4,
                "childRen": []
              },
              {
                "uuid": "b901d8e88d494c49901684efdfd78fa9",
                "categoryName": "111(0)",
                "parentUuid": "i7f477bfbf3f44a797efeae830212320",
                "describeInfo": "",
                "lever": 4,
                "childRen": []
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "uuid": "category000000000000000000000010",
    "categoryName": "知识管理默认二级分类(1)",
    "parentUuid": "category000000000000000000000009",
    "describeInfo": "知识管理默认二级分类",
    "lever": 2,
    "childRen": []
  },
  {
    "uuid": "d5b4dc296a5e47c8bb546fe1ac3a5446",
    "categoryName": "3无123213(0)",
    "parentUuid": "z4440a5127f0492ab3eaeb1a4a98406f",
    "describeInfo": "",
    "lever": 2,
    "childRen": [
      {
        "uuid": "i7f477bfbf3f44a797efeae830212320",
        "categoryName": "tttt(0)",
        "parentUuid": "d5b4dc296a5e47c8bb546fe1ac3a5446",
        "describeInfo": "",
        "lever": 3,
        "childRen": [
          {
            "uuid": "r1f1b3deaf224ea4a3cd732f4d59c43a",
            "categoryName": "bb(0)",
            "parentUuid": "i7f477bfbf3f44a797efeae830212320",
            "describeInfo": "",
            "lever": 4,
            "childRen": []
          },
          {
            "uuid": "b901d8e88d494c49901684efdfd78fa9",
            "categoryName": "111(0)",
            "parentUuid": "i7f477bfbf3f44a797efeae830212320",
            "describeInfo": "",
            "lever": 4,
            "childRen": []
          }
        ]
      }
    ]
  },
  {
    "uuid": "i7f477bfbf3f44a797efeae830212320",
    "categoryName": "tttt(0)",
    "parentUuid": "d5b4dc296a5e47c8bb546fe1ac3a5446",
    "describeInfo": "",
    "lever": 3,
    "childRen": [
      {
        "uuid": "r1f1b3deaf224ea4a3cd732f4d59c43a",
        "categoryName": "bb(0)",
        "parentUuid": "i7f477bfbf3f44a797efeae830212320",
        "describeInfo": "",
        "lever": 4,
        "childRen": []
      },
      {
        "uuid": "b901d8e88d494c49901684efdfd78fa9",
        "categoryName": "111(0)",
        "parentUuid": "i7f477bfbf3f44a797efeae830212320",
        "describeInfo": "",
        "lever": 4,
        "childRen": []
      }
    ]
  },
  {
    "uuid": "r1f1b3deaf224ea4a3cd732f4d59c43a",
    "categoryName": "bb(0)",
    "parentUuid": "i7f477bfbf3f44a797efeae830212320",
    "describeInfo": "",
    "lever": 4,
    "childRen": []
  },
  {
    "uuid": "b901d8e88d494c49901684efdfd78fa9",
    "categoryName": "111(0)",
    "parentUuid": "i7f477bfbf3f44a797efeae830212320",
    "describeInfo": "",
    "lever": 4,
    "childRen": []
  }
]
        Category category = new Category();
        List<Category> categoryList = category.getCategoryList();
        // 方式1
        List<Category> collect = categoryList.stream().filter(c -> c.getPid() == 0).map((cate) -> {
            cate.setChildren(getChildren(cate, categoryList));
            return cate;
        }).collect(Collectors.toList());

        String s = JsonUtil.toJson(collect);
        System.out.println(s);

private List<Category> getChildren(Category root, List<Category> all){
  List<Category> childrenList = all.stream().filter(x -> x.getPid().equals(root.getId())).map((category -> {
  category.setChildren(getChildren(category, all));
  return category;
 })).collect(Collectors.toList());
  return childrenList;
}
pojo:
@Data
public class CategoryTreeVO {
  private Integer id;
  private String name;
  private Integer type;
  private Integer fatherId;
  private List<CategoryTreeVO> nodeCategoryList;
}
@Override
public List<CategoryTreeVO> treeList() {
  List<CategoryTreeVO> treeList = categoryMapperCustom.treeList();
   方式2
  List<CategoryTreeVO> categoryTreeVOS = buildTree100(treeList, 0);
  return categoryTreeVOS;
  }

 public List<CategoryTreeVO> buildTree100(List<CategoryTreeVO> list, Integer pid) {
        List<CategoryTreeVO> trees = new ArrayList<CategoryTreeVO>();
        for (CategoryTreeVO categoryTree : list
        ) {
            if (categoryTree.getFatherId().equals(pid)) {
                List<CategoryTreeVO> nodeList = buildTree100(list, categoryTree.getId());
                categoryTree.setNodeCategoryList(nodeList);
                trees.add(categoryTree);
            }
        }
        return trees;
    }

stream 方式处理递归树形结构

/**
 * @author zhangxiao
 * @qq 490433117
 * @create_date 2023/6/20 17:57
 */
package com.suninfo.test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author zhangxiao
 * @date 2023/6/20 17:57
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Category {
    private Integer id;
    private String name;
    private Integer pid;
    private List<Category> children;

    public Category(Integer id, String name, Integer pid) {
        this.id = id;
        this.name = name;
        this.pid = pid;
    }

    public List<Category> getCategoryList(){
        List<Category> list = new ArrayList<>();
        list.add(new Category(1,"宝鸡市",0));
        list.add(new Category(2,"渭城区",1));
        list.add(new Category(3,"西安市",0));
        list.add(new Category(4,"长安区",3));
        list.add(new Category(5,"韦曲街道",4));
        list.add(new Category(6,"上马营镇",2));
        list.add(new Category(7,"雁塔区",3));
        return list;
    }
}
private List<Category> getChildren(Category root, List<Category> all){
        List<Category> childrenList = all.stream().filter(x -> x.getPid().equals(root.getId())).map((category -> {
            category.setChildren(getChildren(category, all));
            return category;
        })).collect(Collectors.toList());
        return childrenList;
    }

    @Test
    public void index8(){
        Category category = new Category();
        List<Category> categoryList = category.getCategoryList();
        // 方式1
        List<Category> collect = categoryList.stream().filter(c -> c.getPid() == 0).map((cate) -> {
            cate.setChildren(getChildren(cate, categoryList));
            return cate;
        }).collect(Collectors.toList());

        String s = JsonUtil.toJson(collect);
        System.out.println(s);
    }
// 方式1
        List<Category> collect = categoryList.stream().filter(c -> c.getPid() == 0).map((cate) -> {
            cate.setChildren(getChildren(cate, categoryList));
            return cate;
        }).sorted((s1,s2)->{
            Integer a1 = s1.getSort() == null ? 0: s1.getSort();
            Integer a2 = s2.getSort() == null ? 0: s2.getSort();

            return a1 - a2;
        }).collect(Collectors.toList());
 -1升序 在Java中,当两个数进行比较时,返回值为-1表示第一个数小于第二个数。这意味着在升序排序中,如果第一个数小于第二个数,它们的相对顺序将被保持不变。而在降序排序中,如果第一个数小于第二个数,则它们的相对顺序将被颠倒。因此,具体是升序还是降序取决于排序算法和具体实现。在实际使用中,可以根据需求和排序算法的要求来选择应该使用哪个值表示升序或降序。

如何快速、且易懂编写Java递归生成树形菜单结构

gitee.com/itxinfei/gmall/blob/mast...

stream 写法参考

本作品采用《CC 协议》,转载必须注明作者和本文链接
MissYou-Coding
讨论数量: 3

这个写法比PHP简单很多

2年前 评论
MissYou-Coding (楼主) 2年前
PHPer技术栈 (作者) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
Coding Peasant @ 互联网
文章
193
粉丝
10
喜欢
60
收藏
64
排名:600
访问:1.3 万
私信
所有博文
博客标签
社区赞助商