Java Program To Print Employee Details Whose Age Is Greater Than 28

1. Introduction

This Java tutorial demonstrates how to filter and print details of employees based on a specific age condition. It will be particularly useful for HR applications that require filtering employees by age or other criteria.

2. Program Steps

1. Define an Employee class with necessary fields like id, name, age, salary, gender, deptName, and city.

2. Create a main method in a separate class that generates a list of Employee objects.

3. Use Java streams to filter and print details of employees who are older than 28.

3. Code Program

// File: Employee.java
public class Employee {
    private int id;
    private String name;
    private int age;
    private long salary;
    private String gender;
    private String deptName;
    private String city;

    public Employee(int id, String name, int age, long salary, String gender, String deptName, String city) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.gender = gender;
        this.deptName = deptName;
        this.city = city;
    }

    @Override
    public String toString() {
        return String.format("ID: %d, Name: %s, Age: %d, Salary: %d, Gender: %s, Department: %s, City: %s",
                             id, name, age, salary, gender, deptName, city);
    }
}

// File: FilterEmployeesByAge.java
import java.util.*;

public class FilterEmployeesByAge {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee(1, "Aditi", 30, 100000, "F", "HR", "Mumbai"),
            new Employee(2, "Rahul", 25, 130000, "M", "Tech", "Bangalore"),
            new Employee(3, "Vishal", 34, 110000, "M", "Tech", "Mumbai"),
            new Employee(4, "Lakshmi", 45, 150000, "F", "HR", "Bangalore")
        );

        employees.stream()
                 .filter(emp -> emp.age > 28)
                 .forEach(System.out::println);
    }
}

Output:

ID: 1, Name: Aditi, Age: 30, Salary: 100000, Gender: F, Department: HR, City: Mumbai
ID: 3, Name: Vishal, Age: 34, Salary: 110000, Gender: M, Department: Tech, City: Mumbai
ID: 4, Name: Lakshmi, Age: 45, Salary: 150000, Gender: F, Department: HR, City: Bangalore

Explanation:

1. The Employee class is designed to encapsulate all relevant employee data, including age, which is used for filtering.

2. In the FilterEmployeesByAge main method, a list of Employee objects is instantiated.

3. The Java Stream API filters employees whose age is greater than 28 using the filter method with a lambda expression.

4. The forEach method combined with System.out::println prints the details of each employee who meets the age condition.

Comments