Java8 中的Stream遍历树形结构数据

1.实体

@Data
public class Menu {

    //id
    public Integer id;
    //名称
    public String name;
    //父级id
    public Integer parentId;
    //子级集合
    public List childList;

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

2.controller

    public void testMenuTree() {
        List menuDatas = getMenuData();
        List menuTree = menuDatas.stream().filter(m -> m.getParentId() == 0)
                .map((m) -> {
                            m.setChildList(getChildrens(m, menuDatas));
                            return m;
                        }
                ).collect(Collectors.toList());
        System.out.println("菜单树结构:" + JSONUtil.toJsonPrettyStr(menuTree));
    }
 /**
     * 获取子类
     * @param parent
     * @param menuDatas
     * @return
     */
    private List getChildrens(Menu parent, List menuDatas) {
        List childList = menuDatas.stream().filter(m -> {
            return Objects.equals(m.getParentId(), parent.getId());
        }).map((m) -> {
            m.setChildList(getChildrens(m, menuDatas));
            return m;
        }).collect(Collectors.toList());
        return childList;
    }

你可能感兴趣的:(java)