Java8- Get the details of youngest male employee in the product development department

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 09:00:08 Viewed : 241


To get the details of the youngest male employee in the product development department using Java 8, you would need to have attributes in the Employee class for age, gender, and department. Here is an example:

java
import java.util.Arrays; import java.util.List; import java.util.Optional; public class Employee { private String name; private String gender; private int age; private String department; public Employee(String name, String gender, int age, String department) { this.name = name; this.gender = gender; this.age = age; this.department = department; } public String getGender() { return gender; } public int getAge() { return age; } public String getDepartment() { return department; } public static void main(String[] args) { // Sample data List<Employee> employees = Arrays.asList( new Employee("John", "Male", 25, "IT"), new Employee("Jane", "Female", 28, "Finance"), new Employee("Bob", "Male", 22, "Product Development"), new Employee("Alice", "Female", 30, "IT"), new Employee("Charlie", "Male", 24, "Product Development") ); // Get the details of the youngest male employee in the Product Development department using Java 8 streams Optional<Employee> youngestMaleInProductDevelopment = employees.stream() .filter(employee -> "Male".equals(employee.getGender()) && "Product Development".equals(employee.getDepartment())) .min((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge())); // Output the result youngestMaleInProductDevelopment.ifPresent(employee -> System.out.println("Details of the youngest male employee in Product Development: " + "Name: " + employee.getName() + " " + "Age: " + employee.getAge() + " " + "Department: " + employee.getDepartment())); } public String getName() { return name; } }

Output:

yaml
Details of the youngest male employee in Product Development: Name: Bob Age: 22 Department: Product Development

In this example:

  • The Employee class is modified to include attributes for age, gender, and department.
  • Java 8 streams are used to filter employees based on gender and department and then find the youngest male employee in the Product Development department.
  • The result is wrapped in an Optional to handle the case where there might be no matching employee.
  • The details of the youngest male employee in the specified department are then printed to the console.

Search
Related Articles

Leave a Comment: