Given the list of employees, count number of employees with age 25?
You can use the Java 8 Stream API along with the filter()
and count()
methods to count the number of employees with age 25. Here's how you can do it:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Sample list of employees
List<Employee> employees = Arrays.asList(
new Employee("Alice", 25),
new Employee("Bob", 30),
new Employee("Charlie", 20),
new Employee("David", 25)
);
// Count number of employees with age 25
long count = employees.stream()
.filter(employee -> employee.getAge() == 25)
.count();
System.out.println("Number of employees with age 25: " + count);
}
}
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
In this example:
- We define a
Employee
class to represent employees withname
andage
properties. - We create a list of
Employee
objects. - We use the
stream()
method to convert the list into a Stream. - We use the
filter()
method to filter employees whose age is 25. - We use the
count()
method to count the number of employees with age 25. - We print the count to the console.
This code will output the number of employees with age 25:
Number of employees with age 25: 2