Count the number of employees in each department in java8

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:52:14 Viewed : 237


To count the number of employees in each department using Java 8, you would need to have an attribute in the Employee class indicating the department to which each employee belongs. Here is an example:

java
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Employee { private String name; private String department; public Employee(String name, String department) { this.name = name; this.department = department; } public String getDepartment() { return department; } public static void main(String[] args) { // Sample data List<Employee> employees = Arrays.asList( new Employee("John", "HR"), new Employee("Jane", "Finance"), new Employee("Bob", "IT"), new Employee("Alice", "HR"), new Employee("Charlie", "IT") ); // Count the number of employees in each department using Java 8 streams Map<String, Long> employeeCountByDepartment = employees.stream() .collect(Collectors.groupingBy( Employee::getDepartment, Collectors.counting() )); // Output the results employeeCountByDepartment.forEach((department, count) -> System.out.println("Number of employees in " + department + ": " + count)); } }

Output:

javascript
Number of employees in HR: 2 Number of employees in Finance: 1 Number of employees in IT: 2

In this example:

  • The Employee class is modified to include a department attribute.
  • Java 8 streams are used with the Collectors.groupingBy collector to group employees by department.
  • The Collectors.counting downstream collector is used to count the number of employees in each group.
  • The results are stored in a Map<String, Long>, where the keys are department names, and the values are the corresponding employee counts.
  • The results are then printed to the console.

Search
Related Articles

Leave a Comment: