Java 8 中的 Stream 遍历树形结构


public class TreeDemo {

    public static void main(String[] args) {
        testtree();
    }


    public static void testtree() {
        //模拟从数据库查询出来
        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)
                // 设置子节点
                .peek(m -> m.setChildList(getChildrens(m, menus)))
                .collect(Collectors.toList());

        System.out.println("-------转json输出结果-------");
        //System.out.println(collect);
        String jsonString = JSON.toJSONString(collect);
        System.out.println(jsonString);
    }


    /**
     * 递归查询子节点
     *
     * @param root 根节点
     * @param all  所有节点
     * @return 根节点信息
     */
    public static List getChildrens(Menu root, List all) {
        List children = all.stream()
                .filter(m -> Objects.equals(m.getParentId(), root.getId()))
                .peek((m) -> m.setChildList(getChildrens(m, all)))
                .collect(Collectors.toList());
        return children;
    }
}