1. @Data
    2. @Builder
    3. public class Menu {
    4. /**
    5. * id
    6. */
    7. public Integer id;
    8. /**
    9. * 名称
    10. */
    11. public String name;
    12. /**
    13. * 父id ,根节点为0
    14. */
    15. public Integer parentId;
    16. /**
    17. * 子节点信息
    18. */
    19. public List<Menu> childList;
    20. public Menu(Integer id, String name, Integer parentId) {
    21. this.id = id;
    22. this.name = name;
    23. this.parentId = parentId;
    24. }
    25. public Menu(Integer id, String name, Integer parentId, List<Menu> childList) {
    26. this.id = id;
    27. this.name = name;
    28. this.parentId = parentId;
    29. this.childList = childList;
    30. }
    31. }
    1. @Test
    2. public void testtree(){
    3. //模拟从数据库查询出来
    4. List<Menu> menus = Arrays.asList(
    5. new Menu(1,"根节点",0),
    6. new Menu(2,"子节点1",1),
    7. new Menu(3,"子节点1.1",2),
    8. new Menu(4,"子节点1.2",2),
    9. new Menu(5,"根节点1.3",2),
    10. new Menu(6,"根节点2",1),
    11. new Menu(7,"根节点2.1",6),
    12. new Menu(8,"根节点2.2",6),
    13. new Menu(9,"根节点2.2.1",7),
    14. new Menu(10,"根节点2.2.2",7),
    15. new Menu(11,"根节点3",1),
    16. new Menu(12,"根节点3.1",11)
    17. );
    18. //获取父节点
    19. List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
    20. (m) -> {
    21. m.setChildList(getChildrens(m, menus));
    22. return m;
    23. }
    24. ).collect(Collectors.toList());
    25. System.out.println("-------转json输出结果-------");
    26. System.out.println(JSON.toJSON(collect));
    27. }
    28. /**
    29. * 递归查询子节点
    30. * @param root 根节点
    31. * @param all 所有节点
    32. * @return 根节点信息
    33. */
    34. private List<Menu> getChildrens(Menu root, List<Menu> all) {
    35. List<Menu> children = all.stream().filter(m -> {
    36. return Objects.equals(m.getParentId(), root.getId());
    37. }).map((m) -> {
    38. m.setChildList(getChildrens(m, all));
    39. return m;
    40. }
    41. ).collect(Collectors.toList());
    42. return children;
    43. }

    测试结果:
    菜单工具类 - 图1