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 :
- Java 8 – How to find duplicate and its count in a Stream or List ?
- Java 8 – How to remove duplicates from ArrayList ?
- Java 8 – How to remove duplicates from LinkedList ?
- Java 8 – How to find duplicate and its count in an Arrays ?
- Java 8 – How to remove duplicate from Arrays ?
- Java 8 – Various ways to remove duplicate elements from Arrays
- Java 8 – How to find and count duplicate values in a Map or HashMap ?
- Java 8 – Find employee count in each department from the List of employees ?
References:
Happy Coding !!
Happy Learning !!