我有一组部门,其中有一级部门、二级部门、三级部门、四级部门,每个部门有id、parentid、name三个属性,id是部门的序号,parentid是上级部门的id,我需要找到某个部门的所有上级部门组成一个部门全称,比如:一级部门/二级部门/三级部门/四级部门,这样的部门全称。需要用递归的方式实现,需要怎么做
4条回答 默认 最新
- SpringBoot中文社区 2021-09-22 18:06关注
递归,循环都可以完成,我帮你写一个
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); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
- ¥15 找一个网络防御专家,外包的
- ¥100 能不能让两张不同的图片md5值一样,(有尝)
- ¥15 informer代码训练自己的数据集,改参数怎么改
- ¥15 请看一下,学校实验要求,我需要具体代码
- ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
- ¥20 MATLAB绘制两隐函数曲面的交线
- ¥15 求TYPCE母转母转接头24PIN线路板图
- ¥100 国外网络搭建,有偿交流
- ¥15 高价求中通快递查询接口