java实现一个简单树状图结构

用处: 比如菜单结构 公司层级 用于需要递归的数据 方便前端接收
我这存个简单树状编码存redis做缓存
例:

/**
Controller层
*/
   @PostMapping("/tree")
    @LogAnnotation(value = "科目列表-树", operateType = OperateTypeEnum.QUERY)
    @ApiOperation(value = "科目列表-树", httpMethod = "POST")
    public ApiResult tree(@RequestBody @Validated QueryTrialDataDTO queryTrialDataDto) {
        List result = new ArrayList<>();
        RedisTemplate redisTemplate = (RedisTemplate) SpringBeanUtil.getBean("redisTemplate");
        List vos = redisTemplate.opsForList().range("tree_code", 0, -1);
        if (StringUtils.isNotEmpty(vos)) {
            result.addAll(vos);
        } else {
            result.addAll(queryTrialDataService.buildCodeTree(queryTrialDataDto));
            redisTemplate.opsForList().rightPushAll("tree_code", result.toArray());
            redisTemplate.expire("tree_code", 30, TimeUnit.DAYS);
        }
        return ApiResultBuilder.success(result);
    }
 
 
/**
Service层
*/
@Override
    public List> buildCodeTree(QueryTrialDataDTO queryTrialDataDto) {
        int length = 4;
        //我这数据源 是按 1001(一级) 100101 (二级)每级叠加两位 规则排序
        List> codeList = queryTrialDataMapper.getTree();//数据集
        List> topList = codeList.stream()
                .filter(item -> (((long) item.get("length")) == length)).collect(Collectors.toList());
        // 递归查询出所有子集
        addChild(topList, codeList);
        return topList;
    }

    public void addChild(List> topList, List> codeList) {
        for (Map item : topList) {
            //查询子集
            List> child = getChild(codeList, item.get("code").toString(), (long) item.get("length"));
            if (CollectionUtil.isNotEmpty(child)) {
                //插入儿子
                item.put("children", child);
                //递归
                addChild(child, codeList);
            }
        }
    }

 public List> getChild(List> codeList, String code, long length) {
        //每次取长度大于2的
        List> list = codeList.stream().filter(item -> (((long) item.get("length")) == length + 2))
                .collect(Collectors.toList());
        return list.stream()
                .filter(item -> (item.get("code").toString().substring(0, (int) length).equals(code)))
                .collect(Collectors.toList());
    }

结果图


FEJC{0Q4LME%S3`RCBEXCIR.png

你可能感兴趣的:(java实现一个简单树状图结构)