Java Program To Find Highest Salary in the Organisation

1. Introduction

This tutorial will demonstrate how to create a Java program to find the highest salary within an organization. This can help HR to quickly identify the top earners and assist in budget planning and salary reviews.

Key Points

- Utilization of a custom Employee class with a salary attribute.

- Using Java's Stream API to simplify the process of finding the maximum salary.

- Outputting the highest salary found among all employees.

2. Program Steps

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

2. Create a list of Employee instances.

3. Use Java's Stream API to find the highest salary.

4. Print the highest salary.

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;
    private int yearOfJoining;

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

    public long getSalary() {
        return salary;
    }
}

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

public class FindHighestSalary {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee(1, "Aditi", 30, 100000, "F", "HR", "Mumbai", 1995),
            new Employee(2, "Rahul", 25, 130000, "M", "Engineering", "Bangalore", 2000),
            new Employee(3, "Vishal", 34, 110000, "M", "Engineering", "Mumbai", 1998),
            new Employee(4, "Lakshmi", 28, 150000, "F", "HR", "Bangalore", 1992),
            new Employee(5, "Priya", 24, 90000, "F", "Marketing", "Delhi", 2005)
        );

        long highestSalary = employees.stream()
                                      .mapToLong(Employee::getSalary)
                                      .max()
                                      .orElse(0);

        System.out.println("The highest salary in the organization is: " + highestSalary);
    }
}

Output:

The highest salary in the organization is: 150000

Explanation:

1. The Employee class is designed with various attributes, including salary, which is vital for determining the highest earner.

2. A list of Employee instances is created in the FindHighestSalary class, which includes a variety of salary values.

3. The stream().mapToLong().max() pattern is employed to extract the salary attribute from each employee and find the maximum value.

4. The result is printed, showing the highest salary within the organization. If no employees are found or all have a salary of zero, it defaults to zero due to the use of orElse.

Comments