首页 > 基础资料 博客日记

递归遍历树状结构优雅实现

2024-08-07 14:30:03基础资料围观126

本篇文章分享递归遍历树状结构优雅实现,对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识

递归遍历树状结构优雅实现

实体:

@Data
@Builder
public class Menu {
  private Integer id;
  private String name;
  private Integer parentId;
  private List<Menu> childrenList;

  public Menu(Integer id, String name, Integer parentId) {
    this.id = id;
    this.name = name;
    this.parentId = parentId;
  }

  public Menu(Integer id, String name, Integer parentId, List<Menu> childrenList) {
    this.id = id;
    this.name = name;
    this.parentId = parentId;
    this.childrenList = childrenList;
  }
}

实现:

@SpringBootTest
public class RecursionTest {
  @Test
  public void recursion() {
    List<Menu> menus = Arrays.asList(
            new Menu(1, "根节点", 0),
            new Menu(2, "子节点1", 1),
            new Menu(3, "子节点1.1", 2),
            new Menu(4, "子节点1.2", 2),
            new Menu(5, "根节点1.3", 2),
            new Menu(6, "根节点2", 1),
            new Menu(7, "根节点2.1", 6),
            new Menu(8, "根节点2.2", 6),
            new Menu(9, "根节点2.2.1", 7),
            new Menu(10, "根节点2.2.2", 7),
            new Menu(11, "根节点3", 1),
            new Menu(12, "根节点3.1", 11));

    // 获取父节点
    List<Menu> collect = menus.stream()
            .filter(m -> m.getParentId() == 0)
            .peek((m) -> m.setChildrenList(getChildren(m, menus)))
            .collect(Collectors.toList());
    System.out.println(JSONUtil.toJsonStr(collect));
  }

  private List<Menu> getChildren(Menu root, List<Menu> all) {
    return all.stream()
            .filter(m -> Objects.equals(m.getParentId(), root.getId()))
            .peek(m -> m.setChildrenList(getChildren(m, all)))
            .collect(Collectors.toList());
  }

}

文章来源:https://www.cnblogs.com/wendy12138/p/18346623
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云