JAVA8 之递归实现

Java8 简单实现递归 (树形展示)
JAVA8 之递归实现_第1张图片

/**
     * 获取选择弹窗
     * @param prodClassNm   某一层条件   TODO 
     * @param prodType      某类型
     * @return
     */
    public List<ProdClassSelectPopVo> getProdClassSelectPop(String prodClassNm, String prodType) {
        List<ProdClassSelectPopVo> treeList = new ArrayList<>();
        // 获取所有商品分类
        List<ProdClassSelectPopVo> allList = mproductClassListDao.getProdClassSelectPop(prodType);
        if(CollectionUtil.isNotEmpty(allList)){
            // 1、获取所有数据中过滤一级菜单 2、Map中通过递归函数获取一级节点中的子节点列表
            treeList = allList.stream().filter(subNode -> StringUtils.isNullOrEmpty(subNode.getParentClass())
                            && (subNode.getId() + "/").equals(subNode.getPath()))
                    .map(m -> getChild(m,allList,prodClassNm)).collect(Collectors.toList());
        }
        if(StringUtils.isNotEmpty(prodClassNm)){
            treeList = treeList.stream().filter(f -> CollectionUtil.isNotEmpty(f.getChildren().stream()
                    .filter(item -> item.getProdClassNm().contains(prodClassNm)).collect(Collectors.toList()))
            ).collect(Collectors.toList());
        }
        return treeList;
    }
    /**
     * 递归辅助函数
     * @param parent 上级节点
     * @param allList 所有数据
     * @return
     */
    private ProdClassSelectPopVo getChild(ProdClassSelectPopVo parent,List<ProdClassSelectPopVo> allList,String prodClassNm){
        List<ProdClassSelectPopVo> treeVo = allList.stream()
                .filter(subNode -> StringUtils.isNotEmpty(subNode.getParentClass())
                        && subNode.getParentClass().equals(parent.getId())).map(m -> getChild(m,allList,prodClassNm)).collect(Collectors.toList());
                        // && subNode.getPath().equals(parent.getId() + "/" +subNode.getId() + "/")).collect(Collectors.toList());
                //.map(m -> getChild(m,allList))
        if(StringUtils.isNotEmpty(prodClassNm)){
            treeVo = treeVo.stream().filter(f -> f.getProdClassNm().contains(prodClassNm)).collect(Collectors.toList());
        }
        parent.setChildren(treeVo);
        return parent;
    }

你可能感兴趣的:(Java,8,java)