前言:这是一个无限极的递归,可用来查树结构,不过建议最好用于五级一下的分类,如果数据过大的话服务器就…
实体中必要三个字段:id
(分类id)、name
(分类名称)、parentld
(父分类id,顶级分类是0)
废话少说,直接上代码:
方法写在service层方法一:
@Service
public class DemoService {
@Autowired
private DemoMapper demoMapper;
/**
* 获取所有分类
* @return
*/
@Override
public List<Organization> selectTreeList(Organization org) {
// 用boot获取分类的数据 selectAll在springboot中是获取数据表里的所有数据
List<Organization> data = demoMapper.selectAll();
//定义新的list
List<Organization> organizationList = new ArrayList<>();
//先找到所有的一级分类
for (Organization organization : data) {
// 一级菜单的parentId是0
if (organization.getParentId().equals("0")) {
organizationList.add(organization);
}
}
// 为一级菜单设置子菜单,getChild是递归调用的
for (Organization organization : organizationList) {
organization.setTreeList(getChilde(organization.getId(), data));
}
return organizationList;
}
/**
* 递归查找子菜单
*
* @param id 当前菜单id
* @param rootList 要查找的列表
* @return
*/
private List<Organization> getChilde(String id, List<Organization> rootList) {
//子菜单
List<Organization> childList = new ArrayList<>();
for (Organization organization : rootList) {
// 遍历所有节点,将父菜单id与传过来的id比较
if (organization.getParentId().equals(id)) {
childList.add(organization);
}
}
// 把子菜单的子菜单再循环一遍
for (Organization organization : childList) {
organization.setTreeList(getChilde(organization.getId(), rootList));
}
// 递归退出条件
if (childList.size() == 0) {
return null;
}
return childList;
}
}
方法写在service层方法二:
public static List<UserVO> buildTree(List<UserVO> list) {
// 用一个Map来存储所有节点,key为rowId,value为对应的节点对象
Map<Long, UserVO> nodeMap = new HashMap<>();
for (UserVO node : list) {
nodeMap.put(node.getId(), node);
}
// 构建树形结构
List<UserVO> tree = new ArrayList<>();
for (UserVO node : list) {
Long parentId = node.getParentId();
if (parentId==0) { // 根节点
tree.add(node);
} else { // 非根节点
UserVO parentNode = nodeMap.get(parentId);
if (parentNode != null) {
if (parentNode.getChildren() == null) {
parentNode.setChildren(new ArrayList<>());
}
parentNode.getChildren().add(node);
}
}
}
return tree;
}