Java Program To Find if There Any Employees From HR Department

1. Introduction

This tutorial will guide you through creating a Java program to check if there are any employees in the HR department. This kind of check can be useful in HR applications to quickly ascertain the presence of HR staff in the employee database.

Key Points

- Use of a custom Employee class with a deptName attribute.

- Utilization of Java's Stream API to filter employees based on department.

- Using anyMatch to efficiently check for the presence of HR department employees.

2. Program Steps

1. Define the Employee class with necessary attributes, including deptName.

2. Create a main method that initializes a list of Employee objects.

3. Use the Stream API to check if any employees belong to the HR department.

4. Print the result of the check.

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;
    }

    public String getDeptName() {
        return deptName;
    }
}

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

public class CheckHRDepartment {
    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", "Engineering", "Bangalore"),
            new Employee(3, "Vishal", 34, 110000, "M", "Engineering", "Mumbai"),
            new Employee(4, "Lakshmi", 28, 150000, "F", "HR", "Bangalore"),
            new Employee(5, "Priya", 24, 90000, "F", "Marketing", "Delhi")
        );

        boolean hasHREmployees = employees.stream()
                                          .anyMatch(e -> "HR".equals(e.getDeptName()));

        System.out.println("Are there any HR department employees? " + (hasHREmployees ? "Yes" : "No"));
    }
}

Output:

Are there any HR department employees? Yes

Explanation:

1. An Employee class is set up with a deptName field that determines the department to which an employee belongs.

2. In the CheckHRDepartment main method, a list of Employee objects is initialized.

3. The Stream API is employed with the anyMatch method to ascertain whether any employees work in the HR department based on their deptName.

4. The result is a boolean that is then printed, indicating whether HR department employees are present.

Comments