java 如何用递归的方式实现目标

我有一组部门,其中有一级部门、二级部门、三级部门、四级部门,每个部门有id、parentid、name三个属性,id是部门的序号,parentid是上级部门的id,我需要找到某个部门的所有上级部门组成一个部门全称,比如:一级部门/二级部门/三级部门/四级部门,这样的部门全称。需要用递归的方式实现,需要怎么做

递归,循环都可以完成,我帮你写一个

package io.springcloud.test;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.stream.Collectors;

class Department {
    private Integer id;
    private String name;
    private Integer parentid;

    public Department(Integer id, String name, Integer parentid) {
        super();
        this.id = id;
        this.name = name;
        this.parentid = parentid;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getParentid() {
        return parentid;
    }

    public void setParentid(Integer parentid) {
        this.parentid = parentid;
    }
}

public class MainTest {

    public static Map<Integer, Department> DATA = new HashMap<>();

    static {
        DATA.put(1, new Department(1, "部门1", null));
        DATA.put(2, new Department(2, "部门2", 1));
        DATA.put(3, new Department(3, "部门3", 2));
        DATA.put(4, new Department(4, "部门4", 3));
        DATA.put(5, new Department(5, "部门5", null));
        DATA.put(6, new Department(6, "部门6", 1));
        DATA.put(7, new Department(7, "部门7", 5));
    }

    public static void main(String[] args) throws Exception {
        
        MainTest mainTest = new MainTest();
        
        String result = mainTest.list(3, new LinkedList<>()).stream().map(Department::getName).collect(Collectors.joining("/"));
        
        System.out.println(result);  // 部门1/部门2/部门3

    }

    /**
     * 根据ID查询数据
     * @param id
     * @return
     */
    public Department findById(Integer id) {
        return DATA.get(id);
    };

    /**
     * 根据ID查询所有父级部门链
     * @param id
     * @param result
     * @return
     */
    public LinkedList<Department> list(Integer id, LinkedList<Department> result) {
        
        if (id == null) {
            return result;
        }

        Department department = findById(id);

        result.addFirst(department);

        return list(department.getParentid(), result);
    }
}

就是直接判断呢,,

有任何疑问,欢迎来交流

一直判断parentid是否存在于你的数据中,每找到一个就凭借字符串,“上级部门/”

如果最大只有四级部门是固定的话,不建议用递归,实在要用的话
比如一级部门的上级ID是0的话,那就一级一级往上找,找到0的话退出就可以了。


不用递归的话,可以用select查询平铺成四个表,一级部门表,二级部门表,三级部门表,四级部门表。
然后直接对这个四个表关联查名字就可以了。