![]() |
Consider a scenario where you have a dataset containing various salary values, and you need to find the Nth highest salary. This task might arise in applications ranging from financial systems to human resources, where understanding salary distributions is crucial. For Data Manipulation and Processing, Java’s Stream API has proven to be a powerful tool for simplifying complex operations on collections. In this article, we will learn to find nth highest salary using Stream API. N’th Highest Salary Using Stream APIApproach: Java 8’s Stream API streamlines finding the nth highest salary in a list. Its declarative and functional approach makes the solution elegant and efficient. We’ll explore this technique in detail. Step By Step ImplementationStep 1: Create a Map of Employees mapping to their respective salaries.
Step 2: Let’s sort them in descending order by their salaries.
From the above table, we can easily get the nth highest salary from the top. For example, 2nd highest salary is holding by the 2nd row [70,000->Kalam] Below, is the implementation of above problem solution in Java using Stream API and its relevant methods. Java
Output
70000 = [ kalam ] But wait, what if there are employees with same salaries? Will this approach works?? And, answer is big No. Let us check it in the Example Employees with Same Salaries
Now, let’s sort them in descending order with respect their salaries.
Now, for suppose we want to get the third highest salary. If we use the first approach and code we will get [45,000] but the actual 3rd highest salary is [35,000]. Below code is the implementation of this approach by grouping them according to their respective salaries and appending the first approach to it. Java
Output
35000=[Raheem, Chand] By following these steps, developers can harness the power of Java’s Stream API to efficiently find the nth highest salary, making code concise, readable, and maintainable. |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |