1. Introduction
This Java tutorial illustrates how to count the number of employees in each department. This kind of data aggregation is critical for management to analyze departmental resources and workload distribution effectively.
2. Program Steps
1. Define an Employee class with fields such as deptName for department information.
2. Create a main class EmployeeDepartmentCount that populates a list of Employee objects.
3. Use a Map to count and store the number of employees in each department.
4. Print the result.
3. Code Program
// File: Employee.java
public class Employee {
private int id;
private String name;
private int age;
private long salary;
private String gender;
private String deptName;
private String city;
public Employee(int id, String name, int age, long salary, String gender, String deptName, String city) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
this.gender = gender;
this.deptName = deptName;
this.city = city;
}
public String getDeptName() {
return deptName;
}
}
// File: EmployeeDepartmentCount.java
import java.util.*;
import java.util.stream.Collectors;
public class EmployeeDepartmentCount {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(1, "Aditi", 30, 100000, "F", "HR", "Mumbai"),
new Employee(2, "Rahul", 25, 130000, "M", "Engineering", "Bangalore"),
new Employee(3, "Vishal", 34, 110000, "M", "Engineering", "Mumbai"),
new Employee(4, "Lakshmi", 45, 150000, "F", "HR", "Bangalore")
);
Map<String, Long> departmentCount = employees.stream()
.collect(Collectors.groupingBy(Employee::getDeptName, Collectors.counting()));
departmentCount.forEach((deptName, count) -> System.out.println("Department: " + deptName + ", Number of Employees: " + count));
}
}
Output:
Department: HR, Number of Employees: 2 Department: Engineering, Number of Employees: 2
Explanation:
1. The Employee class contains fields for employee details, including the department name.
2. In EmployeeDepartmentCount, a list of Employee objects is created and then processed using the Stream API.
3. The collect method with groupingBy is used to group employees by department, and counting as a downstream collector to count employees per department.
4. The results are then printed, showing the count of employees for each department.
Comments
Post a Comment
Leave Comment