Java 8 – Find employee count in each department ?

In this article, we will discuss how to find employee count in every department using Java 8 Stream API

Find employee count in each department :

Let’s define employee class with 2 attributes namely –

  • name
  • department they belongs to

Employee.java

package in.bench.resources.find.duplicate.count;

public class Employee {

	// member variables
	private String name;
	private String department;


	// 2-arg parameterized constructor
	public Employee(String name, String department) {
		super();
		this.name = name;
		this.department = department;
	}


	// getters & setters
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
}

Now, let’s code/write main class to fetch employee count for each departments

FindNumberOfEmployeesInDepartment.java

package in.bench.resources.find.duplicate.count;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FindNumberOfEmployeesInDepartment {

	// main() method
	public static void main(String[] args) {

		// list of employees
		List<Employee> employees = Arrays.asList(
				new Employee("Pup", "IT"),
				new Employee("Pigeon", "HR"),
				new Employee("Punter", "IT"),
				new Employee("Gilly", "HR"),
				new Employee("Haydo", "IT")
				);


		// find employee count in every department
		Map<String, Long> employeeCountInDepartmentMap = employees
				.stream()
				.collect(Collectors.groupingBy(e -> e.getDepartment(), Collectors.counting()));


		// print to console
		System.out.print("Employee department and its count :- \n" 
				+ employeeCountInDepartmentMap);
	}
}

Output :

Employee department and its count :- 
{HR=2, IT=3}

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java 8 - Find duplicate count from Integer arrays ?
Java 8 – How to find and count duplicate values in a Map or HashMap ?