1. Introduction
This tutorial demonstrates how to count the number of male and female employees in different organizations using Java 8 Streams. This method can help businesses analyze workforce diversity across different branches or departments.
2. Program Steps
1. Define an Employee class with attributes for name, gender, and organization.
2. Create a list of Employee objects.
3. Use Stream operations to count male and female employees by organization.
3. Code Program
import java.util.Arrays;
import java.util.List;
public class EmployeeOrganizationCount {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Rahul Gupta", "Male", "Infosys"),
new Employee("Priya Patil", "Female", "Infosys"),
new Employee("Amit Raj", "Male", "TCS"),
new Employee("Deepika Sharma", "Female", "TCS"),
new Employee("Vijay Kumar", "Male", "Infosys")
);
long malesInInfosys = employees.stream()
.filter(e -> "Male".equals(e.getGender()) && "Infosys".equals(e.getOrganization()))
.count();
long femalesInInfosys = employees.stream()
.filter(e -> "Female".equals(e.getGender()) && "Infosys".equals(e.getOrganization()))
.count();
long malesInTCS = employees.stream()
.filter(e -> "Male".equals(e.getGender()) && "TCS".equals(e.getOrganization()))
.count();
long femalesInTCS = employees.stream()
.filter(e -> "Female".equals(e.getGender()) && "TCS".equals(e.getOrganization()))
.count();
System.out.println("Male employees in Infosys: " + malesInInfosys);
System.out.println("Female employees in Infosys: " + femalesInInfosys);
System.out.println("Male employees in TCS: " + malesInTCS);
System.out.println("Female employees in TCS: " + femalesInTCS);
}
}
class Employee {
private String name;
private String gender;
private String organization;
Employee(String name, String gender, String organization) {
this.name = name;
this.gender = gender;
this.organization = organization;
}
public String getGender() {
return gender;
}
public String getOrganization() {
return organization;
}
}
Output:
Male employees in Infosys: 2 Female employees in Infosys: 1 Male employees in TCS: 1 Female employees in TCS: 1
Explanation:
1. Employee Class: Includes fields for name, gender, and organization to represent an employee.
2. Creating List: A list of Employee objects represents employees from Infosys and TCS.
3. Stream Filters: The stream is filtered by both gender and organization to count male and female employees separately in each company.
4. Output Statements: Print the count of male and female employees in Infosys and TCS, demonstrating how Java Streams can be used for conditional counting in a real-world business.
Comments
Post a Comment
Leave Comment