• 150606

    文章

  • 1200

    评论

  • 13

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

java部门树的递归


部门对象

package com.ytx.demo.tree;

import java.util.ArrayList;
import java.util.List;

public class Department {
private int id;
private String name;
private int parentId;
private List<Department> children = new ArrayList<Department>();

public Department(int id, String name, int parentId) {
    this.id = id;
    this.name = name;
    this.parentId = parentId;
}

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

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

public int getParentId() {
    return parentId;
}

public void setParentId(int parentId) {
    this.parentId = parentId;
}

public List<Department> getChildren() {
    return children;
}

public void setChildren(List<Department> children) {
    this.children = children;
}
}

递归实现

package com.ytx.demo.tree;

import java.util.ArrayList;
import java.util.List;

public class DempartmentThree {
public static void main(String[] args) {
    List<Department> departmentList = new ArrayList<>();
    departmentList.add(new Department(1, "研发部门", 0));
    departmentList.add(new Department(2, "研发团队1", 1));
    departmentList.add(new Department(3, "研发团队2", 1));
    departmentList.add(new Department(4, "财务部门", 0));
    departmentList.add(new Department(5, "财务A部门", 4));
    departmentList.add(new Department(6, "财务B部门", 4));
    departmentList.add(new Department(7, "财务A部门团队1", 5));
    departmentList.add(new Department(8, "财务A部门团队2", 5));
    departmentList.add(new Department(9, "财务B部门团队1", 6));
    departmentList.add(new Department(10, "财务B部门团队2", 6));

    List<Department> listTree = getThree(departmentList,0);
    System.out.println(listTree);
}

private static List<Department> getThree(List<Department> list,int parentId){
    //获取所有子节点
    List<Department> childTreeList = getChildTree(list,parentId);
    for (Department dept:childTreeList) {
        dept.setChildren(getThree(list,dept.getId()));
    }
    return childTreeList;
}

private static List<Department> getChildTree(List<Department> list,int id){
    List<Department> childTree = new ArrayList<>();
    for (Department dept:list) {
        if(dept.getParentId() == id){
            childTree.add(dept);
        }
    }
    return childTree;
}
}

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

1条评论

Loading...
  • yyyz1413L

    部门下面还有员工该怎么继续递归呀。。。。大佬求指教(员工、部门都是数据库里的数据,通过一张映射表关联....)



发表评论

电子邮件地址不会被公开。 必填项已用*标注

自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客