Java8新特性-使用Stream流递归实现遍历树形结构

1.实体类:

package entity; import lombok.Builder; import lombok.Data; import java.util.List; /** * 描述:Menu * * @author 何志鹏 * @ClassName:Menu * @create 2021-03-05 10:42 * Version 1.0 */ @Data @Builder public class Menu { /** * id */ public Integer id; /** * 名称 */ public String name; /** * 父id ,根节点为0 */ public Integer parentId; /** * 子节点信息 */ public List childList; 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 childList) { this.id = id; this.name = name; this.parentId = parentId; this.childList = childList; } }


2.递归组装树形结构:


package com.example.demo; import com.alibaba.fastjson.JSON; import entity.Menu; import java.util.*; import java.util.stream.Collectors; /** * 描述:QrcodeController * * @author 何志鹏 * @ClassName:QrcodeController * @create 2019-05-28 14:06 * Version 1.0 */ public class QrcodeController {public static void main(String[] args) throws Exception{//模拟从数据库查询出来 List 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 collect = menus.stream().filter(m -> m.getParentId() == 0).map( (m) -> { m.setChildList(getChildrens(m, menus)); return m; } ).collect(Collectors.toList()); System.out.println("-------转json输出结果-------"); System.out.println(JSON.toJSONString(collect)); } /** * 递归查询子节点 * @param root根节点 * @param all所有节点 * @return 根节点信息 */ private static List getChildrens(Menu root, List all) { List children = all.stream().filter(m -> { return Objects.equals(m.getParentId(), root.getId()); }).map( (m) -> { m.setChildList(getChildrens(m, all)); return m; } ).collect(Collectors.toList()); return children; }}


3.输出结果:
Java8新特性-使用Stream流递归实现遍历树形结构
文章图片






【Java8新特性-使用Stream流递归实现遍历树形结构】

    推荐阅读