Java 递归查询树形结构

适用于字段parentId存的是上一级,而不是全级的树结构
@Override
    public List getTree(Map paramMap) {
        // 条件查询
        List tree = cmsHolidayMapper.getTree(paramMap);
        // List to Map
        Map map = tree.stream().collect(Collectors.toMap(CmsHoliday::getId, Function.identity()));
        // 查询所有
        List all = cmsHolidayService.findAll();
        // 生成树
        List fisheryList = cmsHolidayTree(all, "0",map,(String) paramMap.get("delFlag"));
        return fisheryList;
    }
参数说明如下:
cmsFisheries:查询出来的全部数据
parentId:父级id
tree:符合条件的数据
delFlag:0:上架,1:下架,2:归档
private List cmsHolidayTree( List cmsHolidays, String parentId,Map tree,String delFlag){
        if (CollectionUtils.isEmpty(tree)){
            return null;
        }
        // 根据getParentId筛选符合条件的数据
        List fisheryList = cmsHolidays.stream().filter(cmsFishery -> cmsFishery.getParentId().equals(parentId))
                .peek(cmsHoliday -> {
                    // 如果条件中包含父级就把子级也放到List条件中
                    if(tree.containsKey(cmsHoliday.getId()) && cmsHoliday.getDelFlag().equals(delFlag) && !tree.containsKey(cmsHoliday.getParentId())){
                        tree.put(cmsHoliday.getId(), cmsHoliday);
                    }else if (tree.containsKey(cmsHoliday.getParentId()) && cmsHoliday.getDelFlag().equals(delFlag)) {
                        tree.put(cmsHoliday.getId(), cmsHoliday);
                    }
                    // 查询是否有子级
                    List list = this.cmsHolidayTree(cmsHolidays, cmsHoliday.getId(), tree,delFlag);
                    // 判断条件中是否包含自己
                    list = list.stream().filter(c -> tree.containsKey(c.getId())).collect(Collectors.toList());
                    // 如果包含自己就把自己去掉,把父级放到条件中
                    list.forEach(c -> tree.remove(c.getId()));
                    if (!CollectionUtils.isEmpty(list)) {
                        tree.put(cmsHoliday.getId(), cmsHoliday);
                    }
                    cmsHoliday.setChildren(list);
                }).collect(Collectors.toList());
        // 筛选符合条件的父级
        return fisheryList.stream().filter(c -> tree.containsKey(c.getId())).collect(Collectors.toList());
    }

 到这里,递归查询树形结构数据就完成了,生成的树结构形式如下:

Java 递归查询树形结构_第1张图片

你可能感兴趣的:(java,spring,boot)