Write a program to find the nth Highest Salary using Java 8

Consider there is an Employee class having fields id, name, and salary. In this post, we will see how to write a program to find nth highest salary using Java 8.

public class Employee {
    private int id;
    private String name;
    private int salary;

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

    public int getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

Let’s see how to write a program for the nth highest salary using Java 8 stream API.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class NthHighestSalaryStream {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "John", 50000));
        employees.add(new Employee(2, "Alice", 60000));
        employees.add(new Employee(3, "Bob", 45000));
        employees.add(new Employee(4, "Eve", 70000));
        employees.add(new Employee(5, "Mike", 55000));

        int n = 2; // Change this to the desired nth highest salary
        
        Integer nthHighestSalary = employees.stream()
            .map(Employee::getSalary)
            .distinct()
            .sorted(Comparator.reverseOrder())
            .skip(n - 1)
            .findFirst()
            .orElse(null);

        System.out.println("Nth highest salary: " + nthHighestSalary);
    }
}

Output:-

Nth highest salary: 60000

Understanding the above program.

  1. employees.stream(): This part creates a stream of Employee objects. A stream is a sequence of elements that can be processed in a pipeline of operations.
  2. .map(Employee::getSalary): This operation maps each Employee object in the stream to its corresponding salary value using the getSalary() method. This results in a stream of salary values.
  3. .distinct(): This operation removes duplicate salary values from the stream. We want distinct salaries because we are looking for the nth highest salary, and duplicates could affect the result.
  4. .sorted(Comparator.reverseOrder()): This operation sorts the distinct salary values in descending order using the Comparator.reverseOrder() comparator. This ensures that the highest salary comes first in the stream.
  5. .skip(n - 1): The skip operation skips the first n - 1 salary values in the sorted stream. Since the stream is already sorted in descending order, this effectively skips the first n - 1 highest salaries, leaving the nth highest salary as the first element in the remaining stream.
  6. .findFirst(): This operation retrieves the first element from the remaining stream. In this case, the first element is the nth highest salary.
  7. .orElse(null): This part specifies a default value to return if the stream is empty (which would happen if there are fewer distinct salaries than the specified n). In this case, if no nth highest salary is found, the default value null is returned.

So, the entire logic combines these operations to find the nth highest salary from the list of employees:

  1. Map each employee to their salary.
  2. Remove duplicate salaries.
  3. Sort salaries in descending order.
  4. Skip the first n - 1 salaries.
  5. Retrieve the first element (nth highest salary) or null if not found.

Let’s see another way to find nth highest salary program in Java.

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class NthHighestSalaryTreeSet {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "John", 50000));
        employees.add(new Employee(2, "Alice", 60000));
        employees.add(new Employee(3, "Bob", 45000));
        employees.add(new Employee(4, "Eve", 70000));
        employees.add(new Employee(5, "Mike", 55000));

        int n = 2; // Change this to the desired nth highest salary
        
        TreeSet<Integer> uniqueSalaries = new TreeSet<>();
        for (Employee employee : employees) {
            uniqueSalaries.add(employee.getSalary());
        }

        if (uniqueSalaries.size() < n) {
            System.out.println("Insufficient unique salaries.");
            return;
        }

        for (int i = 1; i < n; i++) {
            uniqueSalaries.pollLast();
        }

        System.out.println("Nth highest salary: " + uniqueSalaries.last());
    }
}

Output:-

Nth highest salary: 60000

See docs.

That’s all about how to write a program to find the nth Highest Salary using Java 8.