Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:23:04 Viewed : 251
In Java 8, you can use streams and lambda expressions to filter and count the number of male and female employees in an organization. Here is an example with output:
javaimport java.util.Arrays;
import java.util.List;
public class Employee {
private String name;
private String gender;
public Employee(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getGender() {
return gender;
}
public static void main(String[] args) {
// Sample data
List<Employee> employees = Arrays.asList(
new Employee("John", "Male"),
new Employee("Jane", "Female"),
new Employee("Bob", "Male"),
new Employee("Alice", "Female"),
new Employee("Charlie", "Male")
);
// Count male and female employees using Java 8 streams
long maleCount = employees.stream()
.filter(employee -> "Male".equals(employee.getGender()))
.count();
long femaleCount = employees.stream()
.filter(employee -> "Female".equals(employee.getGender()))
.count();
// Output the results
System.out.println("Number of male employees: " + maleCount);
System.out.println("Number of female employees: " + femaleCount);
}
}
Output:
javascriptNumber of male employees: 3
Number of female employees: 2
In this example:
Employee
class has attributes for name
and gender
.main
method with a list of Employee
objects.You can use the Collectors.groupingBy
collector along with the Collectors.counting
downstream collector to group employees by gender and count the number of male and female employees. 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 gender;
public Employee(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getGender() {
return gender;
}
public static void main(String[] args) {
// Sample data
List<Employee> employees = Arrays.asList(
new Employee("John", "Male"),
new Employee("Jane", "Female"),
new Employee("Bob", "Male"),
new Employee("Alice", "Female"),
new Employee("Charlie", "Male")
);
// Group employees by gender and count using Java 8 streams
Map<String, Long> genderCounts = employees.stream()
.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
// Output the results
genderCounts.forEach((gender, count) ->
System.out.println("Number of " + gender.toLowerCase() + " employees: " + count));
}
}
Output:
javascriptNumber of male employees: 3
Number of female employees: 2
In this example:
Collectors.groupingBy
collector is used to group employees by gender.Collectors.counting
downstream collector counts the number of employees in each group.Map<String, Long>
, where the keys are gender ("Male" or "Female") and the values are the corresponding counts.