前几天碰到了一个小问题是关于数据库取出数据然后弄成树状结构类似于目录,首先想到的是递归,于是自己就做了个小demo来测试这个功能。
实体类
@Data
public class CategoryPojo {
private int id;
private String categoryName;//名称
private int parentId;//父类id
private List<CategoryPojo> nodes=new ArrayList<>();//用来存放子类数组·
}
递归方法
public class Recursion {
public static CategoryPojo treeSelect(int id, List<CategoryPojo> bodyList, CategoryPojo category){
List<CategoryPojo> childList =new ArrayList();
for (CategoryPojo c : bodyList) {
if (Objects.equals(id, c.getParentId())) {
treeSelect(c.getId(), bodyList,c);
childList.add(c);
}
}
category.setNodes(childList);
return category;
}
}
因为我是测试所以没有写到数据库中是自己加的假数据,效果一样
public class FindAlls {
public static List<CategoryPojo> findAll() {
List<CategoryPojo> categoryList=new ArrayList<CategoryPojo>();
CategoryPojo category1=new CategoryPojo();
category1.setId(1);
category1.setCategoryName("河南省");
categoryList.add(category1);
CategoryPojo category2=new CategoryPojo();
category2.setId(2);
category2.setCategoryName("河北省");
categoryList.add(category2);
CategoryPojo category3=new CategoryPojo();
category3.setId(3);
category3.setCategoryName("駐馬店市");
category3.setParentId(1);
categoryList.add(category3);
CategoryPojo category4=new CategoryPojo();
category4.setParentId(3);
category4.setId(4);
category4.setCategoryName("汝南縣");
CategoryPojo category5=new CategoryPojo();
category5.setParentId(4);
category5.setId(5);
category5.setCategoryName("我家");
categoryList.add(category4);
CategoryPojo category6=new CategoryPojo();
category6.setParentId(2);
category6.setId(6);
category6.setCategoryName("石家莊");
categoryList.add(category6);
List<CategoryPojo> rootList = new ArrayList<>();
List<CategoryPojo> bodyList = new ArrayList<>();
categoryList.forEach(c ->
{
if (c.getParentId()==0){
rootList.add(c);
}else {
bodyList.add(c);
}
});
List<CategoryPojo> list=new ArrayList<>();
rootList.forEach(
c->{
CategoryPojo category = Recursion.treeSelect(c.getId(), bodyList, c);
list.add(category);
});
return list;
}
public static void main(String[] args) {
List<CategoryPojo> list=findAll();
System.out.println(list);
}
}
结果如下:
[CategoryPojo(id=1, categoryName=河南省, parentId=0, nodes=[CategoryPojo(id=3, categoryName=駐馬店市, parentId=1, nodes=[CategoryPojo(id=4, categoryName=汝南縣, parentId=3, nodes=[])])]), CategoryPojo(id=2, categoryName=河北省, parentId=0, nodes=[CategoryPojo(id=6, categoryName=石家莊, parentId=2, nodes=[])])]
主要是利用递归一层一层把子节点加到上一个节点当中,然后简单地树状图就出来了。