栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中将List转为树形结构

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中将List转为树形结构

Stream流处理

    @Override
    public List listWithTree() {
        // 1、查出所有分类
        List entities = baseMapper.selectList(null);

        // 组装成父子的树形结构

        return entities.stream().filter(m1 ->
            m1.getParentCid() == 0
        ).peek(menu -> {
            menu.setChildren(getChildren(menu, entities));
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
    }

    private List getChildren(CategoryEntity root, List all) {
        return all.stream().filter(m1 -> {
            return m1.getParentCid().equals(root.getCatId());
        }).peek(m1 -> {
            m1.setChildren(getChildren(m1, all));
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
    }

@GetMapping("/getorganddep")
    @ApiOperation(value = "获取机构与部门列表")
    public ResultData getOrgAndDep(UserContext user) {
        GetDepartmentVO vo = new GetDepartmentVO();
        Organization organization = orgRemoteService.get(user.getOrgId());
        BeanUtils.copyProperties(organization, vo);

        List collection = new ArrayList<>();
        collection.add(new QueryCriteria("ancestors", QueryCriteria.LIKE, user.getOrgId()));
        List departments = departmentService.list(collection);

        vo.setDepartments(departments.stream().filter(v -> v.getParentId().equals(user.getOrgId())).peek(t -> {
            t.setChilds(getChildren(departments, t.getId()));
        }).collect(Collectors.toList()));

        return ResultData.OK(vo);
    }

    private List getChildren(List departments, String parentId) {
        return departments.stream().filter(v -> {
            return v.getParentId().equals(parentId);
        }).peek(t -> {
            t.setChilds(getChildren(departments, t.getId()));
        }).collect(Collectors.toList());
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号