Java 8 Interview Questions on Employee Highest Salary

In this blog post, we will explore several common Java 8 interview questions related to processing and analyzing employee salary data. We will cover how to find the average salary of each department, calculate the average and total salary of the organization, identify the highest salary in the organization, and find the second-highest salary. Each topic will include a problem statement, solution steps, code examples, output, and explanation to help you understand the concepts and techniques involved.

Table of Contents

  1. Java 8 - Find the Average Salary of Each Department
  2. Java 8 - Print Average and Total Salary of the Organization
  3. Java 8 - Find the Highest Salary in the Organization
  4. Java 8 - Find the Second Highest Salary in the Organization

1. Java 8 - Find the Average Salary of Each Department

Problem Statement

Given a list of Employee objects, each containing information about the employee's name, department, and salary, calculate the average salary for each department.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name, department, and salary.
  2. Group Employees by Department: Use Collectors.groupingBy to group employees by department.
  3. Calculate the Average Salary: Use Collectors.averagingDouble to compute the average salary for each department.
  4. Print the Results: Display the computed average salary for each department.

Code Example

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Java 8 - Find the Average Salary of Each Department
 * Author: https://www.rameshfadatare.com/
 */
public class AverageSalaryByDepartmentExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", "IT", 50000),
            new Employee("Priya", "HR", 60000),
            new Employee("Raj", "Finance", 70000),
            new Employee("Suman", "IT", 55000),
            new Employee("Kiran", "HR", 65000)
        );

        // Group employees by department and calculate the average salary
        Map<String, Double> averageSalaryByDepartment = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));

        // Print the average salary by department
        averageSalaryByDepartment.forEach((department, avgSalary) -> 
            System.out.println("Department: " + department + ", Average Salary: " + avgSalary));
    }
}

class Employee {
    private String name;
    private String department;
    private double salary;

    public Employee(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }

    public double getSalary() {
        return salary;
    }
}

Output

Department: IT, Average Salary: 52500.0
Department: HR, Average Salary: 62500.0
Department: Finance, Average Salary: 70000.0

Explanation

  • Grouping and Averaging: The code uses the Collectors.groupingBy method to group employees by department and then applies Collectors.averagingDouble to calculate the average salary for each department.
  • Map Result: The result is a map where the key is the department name, and the value is the average salary.
  • forEach(): The forEach() method is used to iterate through the map and print the average salary for each department.

2. Java 8 - Print Average and Total Salary of the Organization

Problem Statement

Given a list of Employee objects, each containing information about the employee's name and salary, calculate both the total and average salary of the organization.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name and salary.
  2. Calculate the Total Salary: Use mapToDouble and sum methods to calculate the total salary.
  3. Calculate the Average Salary: Use Collectors.averagingDouble to calculate the average salary.
  4. Print the Results: Display the total and average salary of the organization.

Code Example

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

/**
 * Java 8 - Print Average and Total Salary of the Organization
 * Author: https://www.rameshfadatare.com/
 */
public class TotalAndAverageSalaryExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", 50000),
            new Employee("Priya", 60000),
            new Employee("Raj", 70000),
            new Employee("Suman", 55000),
            new Employee("Kiran", 65000)
        );

        // Calculate the total salary of the organization
        double totalSalary = employees.stream()
            .mapToDouble(Employee::getSalary)
            .sum();

        // Calculate the average salary of the organization
        OptionalDouble averageSalary = employees.stream()
            .mapToDouble(Employee::getSalary)
            .average();

        // Print the total and average salary
        System.out.println("Total Salary of the Organization: " + totalSalary);
        System.out.println("Average Salary of the Organization: " + 
            (averageSalary.isPresent() ? averageSalary.getAsDouble() : "N/A"));
    }
}

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }
}

Output

Total Salary of the Organization: 300000.0
Average Salary of the Organization: 60000.0

Explanation

  • Total and Average Calculation: The program calculates the total salary using sum() and the average salary using average().
  • OptionalDouble Handling: The average salary is returned as an OptionalDouble, which is checked before retrieving the value to avoid issues with empty lists.
  • Stream API Usage: The program effectively uses the Stream API to process and compute the required salary values.

3. Java 8 - Find the Highest Salary in the Organization

Problem Statement

Given a list of Employee objects, each containing information about the employee's name and salary, find the highest salary among all employees in the organization.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name and salary.
  2. Find the Highest Salary: Use the max method and Comparator to find the employee with the highest salary.
  3. Handle the Result: Properly handle the result, including potential empty lists.
  4. Print the Result: Display the employee with the highest salary.

Code Example

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Comparator;

/**
 * Java 8 - Find the Highest Salary in the Organization
 * Author: https://www.rameshfadatare.com/
 */
public class HighestSalaryExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", 50000),
            new Employee("Priya", 60000),
            new Employee("Raj", 70000),
            new Employee("Suman", 55000),
            new Employee("Kiran", 65000)
        );

        // Find the employee with the highest salary
        Optional<Employee> highestSalaryEmployee = employees.stream()
            .max(Comparator.comparingDouble(Employee::getSalary));

        // Print the employee with the highest salary
        if (highestSalaryEmployee.isPresent()) {
            Employee employee = highestSalaryEmployee.get();
            System.out.println("Employee with the highest salary: " + employee.getName() + 
                               ", Salary: " + employee.getSalary());
        } else {
            System.out.println("No employees found.");
        }
    }
}

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }
}

Output

Employee with the highest salary: Raj, Salary: 70000.0

Explanation

  • Finding Maximum Value: The program uses the max() method with a comparator to identify the employee with the highest salary.
  • Handling Optional: The result is wrapped in an Optional to handle cases where the list might be empty.
  • Comparator Usage: The comparator compares employees based on their salary values.

4. Java 8 - Find the Second Highest Salary in the Organization

Problem Statement

Given a list of Employee objects, each containing information about the employee's name and salary, find the second-highest salary among all employees in the organization.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name and salary.
  2. Sort Salaries in Descending Order: Use the sorted method to sort the salaries in descending order.
  3. Skip the Highest Salary: Use the skip method to bypass the highest salary.
  4. Find the Second-Highest Salary: Use the findFirst method to get the second-highest salary.
  5. Handle the Result: Properly handle the result, including potential empty lists.
  6. Print the Result: Display the second-highest salary and the corresponding employee's name.

Code Example

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Java 8 - Find the Second Highest Salary in the Organization
 * Author: https://www.rameshfadatare.com/
 */
public class SecondHighestSalaryExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", 50000),
            new Employee("Priya", 60000),
            new Employee("Raj", 70000),
            new Employee("Suman", 55000),
            new Employee("Kiran", 65000)
        );

        // Find the employee with the second-highest salary
        Optional<Employee> secondHighestSalaryEmployee = employees.stream()
            .sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())) // Sort by salary in descending order
            .distinct() // Ensure no duplicate salaries are considered
            .skip(1) // Skip the highest salary
            .findFirst(); // Get the second-highest salary

        // Print the employee with the second-highest salary
        if (secondHighestSalaryEmployee.isPresent()) {
            Employee employee = secondHighestSalaryEmployee.get();
            System.out.println("Employee with the second-highest salary: " + employee.getName() +
                               ", Salary: " + employee.getSalary());
        } else {
            System.out.println("No employees found or there is no second-highest salary.");
        }
    }
}

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }
}

Output

Employee with the second-highest salary: Kiran, Salary: 65000.0

Explanation

  • Sorting and Skipping: The program sorts the employees by salary in descending order, skips the first (highest) salary, and retrieves the second-highest salary.
  • Distinct Salaries: The distinct() method ensures that duplicate salaries do not affect the outcome.
  • Optional Handling: The result is wrapped in an Optional to handle cases where there might not be a second-highest salary.

Comments