使用Java程序写一个获取部门组织树,并统计各部门人员数量
时间: 2024-02-26 11:59:33 浏览: 37
好的,我可以为您提供一些思路和代码示例。
首先,需要从数据库或其他数据源获取部门组织结构数据。假设我们使用以下表结构:
```
departments表:
id int
name varchar
parent_id int
employees表:
id int
name varchar
department_id int
```
其中,departments表存储部门信息,包括部门id、名称和父部门id;employees表存储员工信息,包括员工id、姓名和所属部门id。
我们可以使用Java的JDBC API连接数据库并查询数据,示例代码如下:
```java
import java.sql.*;
public class DepartmentTree {
public static void main(String[] args) throws SQLException {
// 连接数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
Statement stmt = conn.createStatement();
// 查询所有部门和员工信息
ResultSet deptRs = stmt.executeQuery("SELECT id, name, parent_id FROM departments");
ResultSet empRs = stmt.executeQuery("SELECT id, name, department_id FROM employees");
// 构建部门树
DepartmentNode root = new DepartmentNode("root");
while (deptRs.next()) {
int id = deptRs.getInt("id");
String name = deptRs.getString("name");
int parentId = deptRs.getInt("parent_id");
DepartmentNode node = new DepartmentNode(name);
root.addChild(id, parentId, node);
}
// 统计各部门人员数量
while (empRs.next()) {
int id = empRs.getInt("id");
String name = empRs.getString("name");
int deptId = empRs.getInt("department_id");
root.addEmployee(deptId, name);
}
// 输出部门组织树及人员数量
root.printTree(0);
root.printEmployeeCount();
}
}
```
上述代码中,我们首先连接数据库并查询部门和员工数据。然后,我们使用DepartmentNode类表示部门节点,并根据部门id和父部门id构建部门树。在添加员工数据时,我们遍历部门树,找到对应的部门节点,然后将员工信息添加到该节点中。最后,我们输出部门组织树及各部门人员数量。
DepartmentNode类的实现如下:
```java
import java.util.*;
public class DepartmentNode {
private String name;
private List<DepartmentNode> children;
private Map<Integer, DepartmentNode> childMap;
private Set<String> employees;
public DepartmentNode(String name) {
this.name = name;
this.children = new ArrayList<>();
this.childMap = new HashMap<>();
this.employees = new HashSet<>();
}
public void addChild(int id, int parentId, DepartmentNode child) {
if (parentId == 0) {
this.children.add(child);
} else {
DepartmentNode parent = childMap.get(parentId);
parent.children.add(child);
}
childMap.put(id, child);
}
public void addEmployee(int deptId, String name) {
DepartmentNode node = childMap.get(deptId);
node.employees.add(name);
}
public void printTree(int indent) {
for (int i = 0; i < indent; i++) {
System.out.print(" ");
}
System.out.println(name);
for (DepartmentNode child : children) {
child.printTree(indent + 1);
}
}
public void printEmployeeCount() {
System.out.println("各部门人员数量:");
for (DepartmentNode child : children) {
int count = child.getEmployeeCount();
System.out.println(child.name + ": " + count);
}
}
public int getEmployeeCount() {
int count = employees.size();
for (DepartmentNode child : children) {
count += child.getEmployeeCount();
}
return count;
}
}
```
在DepartmentNode类中,我们使用children列表和childMap映射表存储子部门节点,并使用employees集合存储员工信息。在addChild方法中,我们根据父部门id将部门节点添加到对应的父节点中。在addEmployee方法中,我们根据部门id将员工添加到对应的部门节点中。在printTree方法中,我们使用递归方式输出部门组织树。在printEmployeeCount和getEmployeeCount方法中,我们使用递归方式统计各部门人员数量。
希望这个示例能对您有所帮助!