递归查询类目,组装成树形结构

首先是实体的:

public class PortalClassVO implements Serializable{

@ApiModelProperty(value = "类目编码")
private String classCode;

@ApiModelProperty(value = "类目名称")
private String className;

@ApiModelProperty(value = "上级类目")
private String parentId;

@ApiModelProperty(value = "类目说明")
private String classDesc;

@ApiModelProperty(value = "是否叶子类目  0否  1  是")
private Integer ifLeaf;

@ApiModelProperty(value = "子节点")
private List childList;

下面是:在数据库查询出全部类目数据,如何组装成树形结构返回给前端
//

//获取所有类目数据
 List vos= portalClassMapper.pageList(query);
 
 //查询树结构
 List returnList = converterTreeList(vos);

    public  List converterTreeList(List vos){
        List rootList = new ArrayList<>(); //根节点对象存放到这里
        List bodyList = new ArrayList<>(); //其他节点存放到这里,可以包含根节点

        for(PortalClassVO vo : vos){
            if(vo != null ){
                if("0".equals(vo.getParentId())){
                    rootList.add(vo);
                }else{
                    bodyList.add(vo);
                }
            }
        }

        List stc = getTree(rootList,bodyList);//组装的树返给前端

        return stc;
    }

 public List getTree(List rootList,List bodyList){

        if(CollectionUtil.isNotEmpty(bodyList) && CollectionUtil.isNotEmpty(rootList)){
            Map map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree ->{ getChild(beanTree,map,bodyList); });
            return rootList;
        }

        if(CollectionUtil.isNotEmpty(rootList)){
            return  rootList;
        }else{
            return bodyList;
        }
    }

 public void getChild(PortalClassVO treeDto , Map map, List bodyList){
        List childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getId()))
                .filter(c -> c.getParentId().equals(treeDto.getId()))
                .forEach(c -> {
                    map.put(c.getId(),c.getParentId());
                    getChild(c,map,bodyList);
                    childList.add(c);
                });
        treeDto.setChildList(childList);//子数据集

    }

你可能感兴趣的:(Java)