Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:52:14 Viewed : 574
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:
javaimport 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:
javascriptNumber of employees in HR: 2
Number of employees in Finance: 1
Number of employees in IT: 2
In this example:
Employee
class is modified to include a department
attribute.Collectors.groupingBy
collector to group employees by department.Collectors.counting
downstream collector is used to count the number of employees in each group.Map<String, Long>
, where the keys are department names, and the values are the corresponding employee counts.