需求:求某一分类下的所有子孙分类,以树的结果集返回
表结构:包含父类ID,父类路径,层级数
非递归方法思路:一次性将所有子孙的结果捞出,通过排序的方式(按层级数)排序,通过遍历整个结果集以map形式拼装结果
递归思路:查找子分类,如果子分类结果集不为空,记录当前分类数据,重复上述
非递归关键代码:(YY哥的代码)
public List<BaikeClassEntity> tranformTree(List<BaikeClassEntity> originalList) {
// 根据parentlevel 升序排序
Collections.sort(originalList);
List<BaikeClassEntity> list = new ArrayList<>();
HashMap<Integer,BaikeClassEntity> map = new HashMap<>();
for (BaikeClassEntity baiKeClass: originalList) {
BaikeClassEntity parent = map.get(baiKeClass.getParentid());
if (parent == null) {
list.add(baiKeClass);
} else {
parent.getChildrens().add(baiKeClass);
}
map.put(baiKeClass.getId(),baiKeClass);
}
return list;
}
实体类
public class BaikeClassEntity implements Serializable, Comparable<BaikeClassEntity> {
private static final long serialVersionUID = 1L;
数据库字段
@Transient
@TableField(exist = false)
private List<BaikeClassEntity> childrens = new ArrayList<>();
@Override
// 根据parentlevels 排序
public int compareTo(BaikeClassEntity o) {
return this.parentlevels - o.parentlevels;
}
}
递归代码:
public List<Tree> test(Integer id){
List<Tree> tree =new ArrayList<>();
List<BaikeClassEntity> list =classService.list(new QueryWrapper<BaikeClassEntity>().eq("ParentID",id)
.eq("MarkStatus",0));
if(list!=null && !list.isEmpty()){
for(BaikeClassEntity entity:list){
Tree t =new Tree();
t.setId(entity.getId());
t.setTitle(entity.getTitle());
t.setChild(test(entity.getId()));
tree.add(t);
}
}
return tree;
}
实体:
public class Tree implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String title;
private List<Tree> child;
}
总结:递归方法虽然简便,但是由于递归时多次查询数据库,查询产生的耗时和查找次数成比例,所以不适合这种情况,非递归的方法由于只有一次查询,数据量偏小,耗时也相比递归方法少很多